From 5b380e45468b5e7f1d320d7979b2b74847d61aa6 Mon Sep 17 00:00:00 2001 From: Yevhen Husak Date: Sun, 8 Feb 2026 01:10:44 +0000 Subject: [PATCH 1/2] feat: add server-synced user preferences infrastructure (#484) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - introduce the foundational layer for persisting user preferences to the server - add UserPreferencesSchema and shared types for user preferences - add client-only sync composable with debounced saves, route guard flush, and sendBeacon fallback - integrate server sync into useSettings and migrate to shared UserPreferences type - extract generic localStorage helpers, migrate consumers, remove usePreferencesProvider --- .../useLocalStorageHashProvider.ts | 34 ++++ app/composables/usePackageListPreferences.ts | 7 +- app/composables/usePreferencesProvider.ts | 100 ------------ app/composables/useSettings.ts | 123 ++++++++------ .../useUserPreferencesSync.client.ts | 154 ++++++++++++++++++ app/utils/storage.ts | 34 ++++ modules/cache.ts | 3 + nuxt.config.ts | 5 + server/api/user/preferences.get.ts | 15 ++ server/api/user/preferences.put.ts | 20 +++ .../preferences/user-preferences-store.ts | 49 ++++++ shared/schemas/userPreferences.ts | 43 +++++ 12 files changed, 431 insertions(+), 156 deletions(-) create mode 100644 app/composables/useLocalStorageHashProvider.ts delete mode 100644 app/composables/usePreferencesProvider.ts create mode 100644 app/composables/useUserPreferencesSync.client.ts create mode 100644 app/utils/storage.ts create mode 100644 server/api/user/preferences.get.ts create mode 100644 server/api/user/preferences.put.ts create mode 100644 server/utils/preferences/user-preferences-store.ts create mode 100644 shared/schemas/userPreferences.ts diff --git a/app/composables/useLocalStorageHashProvider.ts b/app/composables/useLocalStorageHashProvider.ts new file mode 100644 index 000000000..def5980e2 --- /dev/null +++ b/app/composables/useLocalStorageHashProvider.ts @@ -0,0 +1,34 @@ +import { createLocalStorageProvider } from '~/utils/storage' + +export function useLocalStorageHashProvider(key: string, defaultValue: T) { + const provider = createLocalStorageProvider(key) + const data = ref(defaultValue) + + onMounted(() => { + const stored = provider.get() + if (stored) { + data.value = { ...defaultValue, ...stored } + } + }) + + function save() { + provider.set(data.value) + } + + function reset() { + data.value = { ...defaultValue } + provider.remove() + } + + function update(key: K, value: T[K]) { + data.value[key] = value + save() + } + + return { + data, + save, + reset, + update, + } +} diff --git a/app/composables/usePackageListPreferences.ts b/app/composables/usePackageListPreferences.ts index 653f3c626..0eec9260e 100644 --- a/app/composables/usePackageListPreferences.ts +++ b/app/composables/usePackageListPreferences.ts @@ -11,18 +11,18 @@ import type { } from '#shared/types/preferences' import { DEFAULT_COLUMNS, DEFAULT_PREFERENCES } from '#shared/types/preferences' +const STORAGE_KEY = 'npmx-list-prefs' + /** * Composable for managing package list display preferences * Persists to localStorage and provides reactive state - * */ export function usePackageListPreferences() { const { data: preferences, - isHydrated, save, reset, - } = usePreferencesProvider(DEFAULT_PREFERENCES) + } = useLocalStorageHashProvider(STORAGE_KEY, DEFAULT_PREFERENCES) // Computed accessors for common properties const viewMode = computed({ @@ -90,7 +90,6 @@ export function usePackageListPreferences() { return { // Raw preferences preferences, - isHydrated, // Individual properties with setters viewMode, diff --git a/app/composables/usePreferencesProvider.ts b/app/composables/usePreferencesProvider.ts deleted file mode 100644 index c01b7fdb2..000000000 --- a/app/composables/usePreferencesProvider.ts +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Abstraction for preferences storage - * Currently uses localStorage, designed for future user prefs API - */ - -const STORAGE_KEY = 'npmx-list-prefs' - -interface StorageProvider { - get: () => T | null - set: (value: T) => void - remove: () => void -} - -/** - * Creates a localStorage-based storage provider - */ -function createLocalStorageProvider(key: string): StorageProvider { - return { - get: () => { - if (import.meta.server) return null - try { - const stored = localStorage.getItem(key) - if (stored) { - return JSON.parse(stored) as T - } - } catch { - // Corrupted data, remove it - localStorage.removeItem(key) - } - return null - }, - set: (value: T) => { - if (import.meta.server) return - try { - localStorage.setItem(key, JSON.stringify(value)) - } catch { - // Storage full or other error, fail silently - } - }, - remove: () => { - if (import.meta.server) return - localStorage.removeItem(key) - }, - } -} - -// Future: API-based provider would look like this: -// function createApiStorageProvider(endpoint: string): StorageProvider { -// return { -// get: async () => { /* fetch from API */ }, -// set: async (value) => { /* POST to API */ }, -// remove: async () => { /* DELETE from API */ }, -// } -// } - -/** - * Composable for managing preferences storage - * Abstracts the storage mechanism to allow future migration to API-based storage - * - */ -export function usePreferencesProvider(defaultValue: T) { - const provider = createLocalStorageProvider(STORAGE_KEY) - const data = ref(defaultValue) as Ref - const isHydrated = shallowRef(false) - - // Load from storage on client - onMounted(() => { - const stored = provider.get() - if (stored) { - // Merge stored values with defaults to handle schema evolution - data.value = { ...defaultValue, ...stored } - } - isHydrated.value = true - }) - - // Persist changes - function save() { - provider.set(data.value) - } - - // Reset to defaults - function reset() { - data.value = { ...defaultValue } - provider.remove() - } - - // Update specific keys - function update(key: K, value: T[K]) { - data.value[key] = value - save() - } - - return { - data, - isHydrated, - save, - reset, - update, - } -} diff --git a/app/composables/useSettings.ts b/app/composables/useSettings.ts index 7bf06a803..65f38b6f7 100644 --- a/app/composables/useSettings.ts +++ b/app/composables/useSettings.ts @@ -1,58 +1,23 @@ import type { RemovableRef } from '@vueuse/core' import { useLocalStorage } from '@vueuse/core' import { ACCENT_COLORS } from '#shared/utils/constants' -import type { LocaleObject } from '@nuxtjs/i18n' import { BACKGROUND_THEMES } from '#shared/utils/constants' - -type BackgroundThemeId = keyof typeof BACKGROUND_THEMES - -type AccentColorId = keyof typeof ACCENT_COLORS.light - -/** - * Application settings stored in localStorage - */ -export interface AppSettings { - /** Display dates as relative (e.g., "3 days ago") instead of absolute */ - relativeDates: boolean - /** Include @types/* package in install command for packages without built-in types */ - includeTypesInInstall: boolean - /** Accent color theme */ - accentColorId: AccentColorId | null - /** Preferred background shade */ - preferredBackgroundTheme: BackgroundThemeId | null - /** Hide platform-specific packages (e.g., @scope/pkg-linux-x64) from search results */ - hidePlatformPackages: boolean - /** User-selected locale */ - selectedLocale: LocaleObject['code'] | null - sidebar: { - collapsed: string[] - } -} - -const DEFAULT_SETTINGS: AppSettings = { - relativeDates: false, - includeTypesInInstall: true, - accentColorId: null, - hidePlatformPackages: true, - selectedLocale: null, - preferredBackgroundTheme: null, - sidebar: { - collapsed: [], - }, -} +import { + DEFAULT_USER_PREFERENCES, + type AccentColorId, + type BackgroundThemeId, + type UserPreferences, +} from '#shared/schemas/userPreferences' const STORAGE_KEY = 'npmx-settings' -// Shared settings instance (singleton per app) -let settingsRef: RemovableRef | null = null +let settingsRef: RemovableRef | null = null +let syncInitialized = false -/** - * Composable for managing application settings with localStorage persistence. - * Settings are shared across all components that use this composable. - */ +// TODO: After discussion with the team, this will be replaced with a proper persistent solution (LS + server sync) export function useSettings() { if (!settingsRef) { - settingsRef = useLocalStorage(STORAGE_KEY, DEFAULT_SETTINGS, { + settingsRef = useLocalStorage(STORAGE_KEY, DEFAULT_USER_PREFERENCES, { mergeDefaults: true, }) } @@ -62,18 +27,72 @@ export function useSettings() { } } -/** - * Composable for accessing just the relative dates setting. - * Useful for components that only need to read this specific setting. - */ +// TODO: Name to be changed +export function useSettingsSync() { + const { settings } = useSettings() + const { + isAuthenticated, + status, + lastSyncedAt, + error, + loadFromServer, + scheduleSync, + setupRouteGuard, + setupBeforeUnload, + } = useUserPreferencesSync() + + const isSyncing = computed(() => status.value === 'syncing') + const isSynced = computed(() => status.value === 'synced') + const hasError = computed(() => status.value === 'error') + + async function initializeSync(): Promise { + if (syncInitialized || import.meta.server) return + + setupRouteGuard(() => settings.value) + setupBeforeUnload(() => settings.value) + + if (isAuthenticated.value) { + const serverPrefs = await loadFromServer() + Object.assign(settings.value, serverPrefs) + } + + watch( + settings, + newSettings => { + if (isAuthenticated.value) { + scheduleSync(newSettings) + } + }, + { deep: true }, + ) + + watch(isAuthenticated, async newIsAuth => { + if (newIsAuth) { + const serverPrefs = await loadFromServer() + Object.assign(settings.value, serverPrefs) + } + }) + + syncInitialized = true + } + + return { + settings, + isAuthenticated, + isSyncing, + isSynced, + hasError, + syncError: error, + lastSyncedAt, + initializeSync, + } +} + export function useRelativeDates() { const { settings } = useSettings() return computed(() => settings.value.relativeDates) } -/** - * Composable for managing accent color. - */ export function useAccentColor() { const { settings } = useSettings() const colorMode = useColorMode() diff --git a/app/composables/useUserPreferencesSync.client.ts b/app/composables/useUserPreferencesSync.client.ts new file mode 100644 index 000000000..9b6771153 --- /dev/null +++ b/app/composables/useUserPreferencesSync.client.ts @@ -0,0 +1,154 @@ +import type { UserPreferences } from '#shared/schemas/userPreferences' +import { DEFAULT_USER_PREFERENCES } from '#shared/schemas/userPreferences' + +const SYNC_DEBOUNCE_MS = 2000 + +type SyncStatus = 'idle' | 'syncing' | 'synced' | 'error' + +interface PreferencesSyncState { + status: Ref + lastSyncedAt: Ref + error: Ref +} + +let syncStateInstance: PreferencesSyncState | null = null +let pendingSavePromise: Promise | null = null +let hasPendingChanges = false +let debounceTimeoutId: ReturnType | null = null + +function getSyncState(): PreferencesSyncState { + if (!syncStateInstance) { + syncStateInstance = { + status: ref('idle'), + lastSyncedAt: ref(null), + error: ref(null), + } + } + return syncStateInstance +} + +async function fetchServerPreferences(): Promise { + try { + const response = await $fetch('/api/user/preferences', { + method: 'GET', + }) + return response + } catch { + return null + } +} + +async function saveToServer(preferences: UserPreferences): Promise { + const state = getSyncState() + state.status.value = 'syncing' + state.error.value = null + + try { + await $fetch('/api/user/preferences', { + method: 'PUT', + body: preferences, + }) + state.status.value = 'synced' + state.lastSyncedAt.value = new Date() + hasPendingChanges = false + return true + } catch (err) { + state.status.value = 'error' + state.error.value = err instanceof Error ? err.message : 'Failed to save preferences' + return false + } +} + +function cancelPendingDebounce(): void { + if (debounceTimeoutId) { + clearTimeout(debounceTimeoutId) + debounceTimeoutId = null + } +} + +export function useUserPreferencesSync() { + const { user } = useAtproto() + const state = getSyncState() + const router = useRouter() + + const isAuthenticated = computed(() => !!user.value?.did) + + function scheduleSync(preferences: UserPreferences): void { + if (!isAuthenticated.value) return + + hasPendingChanges = true + cancelPendingDebounce() + + debounceTimeoutId = setTimeout(async () => { + debounceTimeoutId = null + pendingSavePromise = saveToServer(preferences) + await pendingSavePromise + pendingSavePromise = null + }, SYNC_DEBOUNCE_MS) + } + + async function loadFromServer(): Promise { + if (!isAuthenticated.value) { + return { ...DEFAULT_USER_PREFERENCES } + } + + state.status.value = 'syncing' + const serverPreferences = await fetchServerPreferences() + + if (serverPreferences) { + state.status.value = 'synced' + state.lastSyncedAt.value = new Date() + return serverPreferences + } + + state.status.value = 'idle' + return { ...DEFAULT_USER_PREFERENCES } + } + + async function flushPendingSync(preferences: UserPreferences): Promise { + if (!isAuthenticated.value || !hasPendingChanges) return + + cancelPendingDebounce() + + if (pendingSavePromise) { + await pendingSavePromise + } else { + await saveToServer(preferences) + } + } + + function setupRouteGuard(getPreferences: () => UserPreferences): void { + router.beforeEach(async (_to, _from, next) => { + if (hasPendingChanges && isAuthenticated.value) { + await flushPendingSync(getPreferences()) + } + next() + }) + } + + function setupBeforeUnload(getPreferences: () => UserPreferences): void { + if (import.meta.server) return + + window.addEventListener('beforeunload', () => { + if (hasPendingChanges && isAuthenticated.value) { + const preferences = getPreferences() + navigator.sendBeacon( + '/api/user/preferences', + new Blob([JSON.stringify(preferences)], { type: 'application/json' }), + ) + } + }) + } + + return { + isAuthenticated, + status: state.status, + lastSyncedAt: state.lastSyncedAt, + error: state.error, + loadFromServer, + scheduleSync, + flushPendingSync, + setupRouteGuard, + setupBeforeUnload, + } +} diff --git a/app/utils/storage.ts b/app/utils/storage.ts new file mode 100644 index 000000000..9706226a3 --- /dev/null +++ b/app/utils/storage.ts @@ -0,0 +1,34 @@ +export interface StorageProvider { + get: () => T | null + set: (value: T) => void + remove: () => void +} + +export function createLocalStorageProvider(key: string): StorageProvider { + return { + get: () => { + if (import.meta.server) return null + try { + const stored = localStorage.getItem(key) + if (stored) { + return JSON.parse(stored) as T + } + } catch { + localStorage.removeItem(key) + } + return null + }, + set: (value: T) => { + if (import.meta.server) return + try { + localStorage.setItem(key, JSON.stringify(value)) + } catch { + // Storage full or other error, fail silently + } + }, + remove: () => { + if (import.meta.server) return + localStorage.removeItem(key) + }, + } +} diff --git a/modules/cache.ts b/modules/cache.ts index a2e7c3a41..bb7332a41 100644 --- a/modules/cache.ts +++ b/modules/cache.ts @@ -42,6 +42,9 @@ export default defineNuxtModule({ const env = process.env.VERCEL_ENV nitroConfig.storage.atproto = env === 'production' ? upstash : { driver: 'vercel-runtime-cache' } + + nitroConfig.storage['user-preferences'] = + env === 'production' ? upstash : { driver: 'vercel-runtime-cache' } }) }, }) diff --git a/nuxt.config.ts b/nuxt.config.ts index e25a9b79f..6ff3e25a2 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -87,6 +87,7 @@ export default defineNuxtConfig({ // never cache '/api/auth/**': { isr: false, cache: false }, '/api/social/**': { isr: false, cache: false }, + '/api/user/**': { isr: false, cache: false }, '/api/opensearch/suggestions': { isr: { expiration: 60 * 60 * 24 /* one day */, @@ -156,6 +157,10 @@ export default defineNuxtConfig({ driver: 'fsLite', base: './.cache/atproto', }, + 'user-preferences': { + driver: 'fsLite', + base: './.cache/user-preferences', + }, }, typescript: { tsConfig: { diff --git a/server/api/user/preferences.get.ts b/server/api/user/preferences.get.ts new file mode 100644 index 000000000..3f660ff57 --- /dev/null +++ b/server/api/user/preferences.get.ts @@ -0,0 +1,15 @@ +import { safeParse } from 'valibot' +import { PublicUserSessionSchema } from '#shared/schemas/publicUserSession' +import { DEFAULT_USER_PREFERENCES } from '#shared/schemas/userPreferences' +import { useUserPreferencesStore } from '#server/utils/preferences/user-preferences-store' + +export default eventHandlerWithOAuthSession(async (event, oAuthSession, serverSession) => { + const session = safeParse(PublicUserSessionSchema, serverSession.data.public) + if (!session.success) { + throw createError({ statusCode: 401, message: 'Unauthorized' }) + } + + const preferences = await useUserPreferencesStore().get(session.output.did) + + return preferences ?? { ...DEFAULT_USER_PREFERENCES, updatedAt: new Date().toISOString() } +}) diff --git a/server/api/user/preferences.put.ts b/server/api/user/preferences.put.ts new file mode 100644 index 000000000..9ab6e8558 --- /dev/null +++ b/server/api/user/preferences.put.ts @@ -0,0 +1,20 @@ +import { safeParse } from 'valibot' +import { PublicUserSessionSchema } from '#shared/schemas/publicUserSession' +import { UserPreferencesSchema } from '#shared/schemas/userPreferences' +import { useUserPreferencesStore } from '#server/utils/preferences/user-preferences-store' + +export default eventHandlerWithOAuthSession(async (event, oAuthSession, serverSession) => { + const session = safeParse(PublicUserSessionSchema, serverSession.data.public) + if (!session.success) { + throw createError({ statusCode: 401, message: 'Unauthorized' }) + } + + const settings = safeParse(UserPreferencesSchema, await readBody(event)) + if (!settings.success) { + throw createError({ statusCode: 400, message: 'Invalid settings format' }) + } + + await useUserPreferencesStore().set(session.output.did, settings.output) + + return { success: true } +}) diff --git a/server/utils/preferences/user-preferences-store.ts b/server/utils/preferences/user-preferences-store.ts new file mode 100644 index 000000000..5fed6ff38 --- /dev/null +++ b/server/utils/preferences/user-preferences-store.ts @@ -0,0 +1,49 @@ +import type { UserPreferences } from '#shared/schemas/userPreferences' +import { + USER_PREFERENCES_STORAGE_BASE, + DEFAULT_USER_PREFERENCES, +} from '#shared/schemas/userPreferences' + +export class UserPreferencesStore { + private readonly storage = useStorage(USER_PREFERENCES_STORAGE_BASE) + + async get(did: string): Promise { + const result = await this.storage.getItem(did) + return result ?? null + } + + async set(did: string, preferences: UserPreferences): Promise { + const withTimestamp: UserPreferences = { + ...preferences, + updatedAt: new Date().toISOString(), + } + await this.storage.setItem(did, withTimestamp) + } + + async merge(did: string, partial: Partial): Promise { + const existing = await this.get(did) + const base = existing ?? { ...DEFAULT_USER_PREFERENCES } + + const merged: UserPreferences = { + ...base, + ...partial, + updatedAt: new Date().toISOString(), + } + + await this.set(did, merged) + return merged + } + + async delete(did: string): Promise { + await this.storage.removeItem(did) + } +} + +let storeInstance: UserPreferencesStore | null = null + +export function useUserPreferencesStore(): UserPreferencesStore { + if (!storeInstance) { + storeInstance = new UserPreferencesStore() + } + return storeInstance +} diff --git a/shared/schemas/userPreferences.ts b/shared/schemas/userPreferences.ts new file mode 100644 index 000000000..241016fc8 --- /dev/null +++ b/shared/schemas/userPreferences.ts @@ -0,0 +1,43 @@ +import { object, string, boolean, nullable, optional, picklist, type InferOutput } from 'valibot' +import { ACCENT_COLORS, BACKGROUND_THEMES } from '#shared/utils/constants' + +const AccentColorIdSchema = picklist(Object.keys(ACCENT_COLORS.light) as [string, ...string[]]) + +const BackgroundThemeIdSchema = picklist(Object.keys(BACKGROUND_THEMES) as [string, ...string[]]) + +export const UserPreferencesSchema = object({ + /** Display dates as relative (e.g., "3 days ago") instead of absolute */ + relativeDates: optional(boolean()), + /** Include @types/* package in install command for packages without built-in types */ + includeTypesInInstall: optional(boolean()), + /** Accent color theme ID (e.g., "rose", "amber", "emerald") */ + accentColorId: optional(nullable(AccentColorIdSchema)), + /** Preferred background shade */ + preferredBackgroundTheme: optional(nullable(BackgroundThemeIdSchema)), + /** Hide platform-specific packages (e.g., @scope/pkg-linux-x64) from search results */ + hidePlatformPackages: optional(boolean()), + /** User-selected locale code (e.g., "en", "de", "ja") */ + selectedLocale: optional(nullable(string())), + /** Timestamp of last update (ISO 8601) - managed by server */ + updatedAt: optional(string()), +}) + +export type UserPreferences = InferOutput + +export type AccentColorId = keyof typeof ACCENT_COLORS.light +export type BackgroundThemeId = keyof typeof BACKGROUND_THEMES + +/** + * Default user preferences. + * Used when creating new user preferences or merging with partial updates. + */ +export const DEFAULT_USER_PREFERENCES: Required> = { + relativeDates: false, + includeTypesInInstall: true, + accentColorId: null, + preferredBackgroundTheme: null, + hidePlatformPackages: true, + selectedLocale: null, +} + +export const USER_PREFERENCES_STORAGE_BASE = 'npmx-kv-user-preferences' From 55c4157f5c8d711ed040de1f4e3d62bc4b9c4215 Mon Sep 17 00:00:00 2001 From: Yevhen Husak Date: Mon, 9 Feb 2026 01:03:45 +0000 Subject: [PATCH 2/2] feat: replace useSettings with useUserPreferences - extract sidebar collapsed state into separate `usePackageSidebarPreferences` composable - add `preferences-sync.client.ts` plugin for early color mode + server sync init - wrap theme select in `` to prevent SSR hydration mismatch - show sync status indicator on settings page for authenticated users - add `useColorModePreference` composable to sync color mode with `@nuxtjs/color-mode` --- app/components/CollapsibleSection.vue | 15 +- app/components/Settings/AccentColorPicker.vue | 6 +- app/components/Settings/BgThemePicker.vue | 4 +- app/composables/useInstallCommand.ts | 4 +- .../usePackageSidebarPreferences.ts | 24 +++ app/composables/useSettings.ts | 150 ------------------ app/composables/useUserPreferences.ts | 133 ++++++++++++++++ app/composables/useUserPreferencesProvider.ts | 97 +++++++++++ app/pages/search.vue | 4 +- app/pages/settings.vue | 80 +++++++--- app/plugins/i18n-loader.client.ts | 18 +-- app/plugins/preferences-sync.client.ts | 13 ++ app/utils/prehydrate.ts | 12 +- i18n/locales/en.json | 6 +- lunaria/files/en-GB.json | 6 +- lunaria/files/en-US.json | 6 +- shared/schemas/userPreferences.ts | 6 + test/nuxt/components/DateTime.spec.ts | 6 +- test/nuxt/components/compare/FacetRow.spec.ts | 6 +- .../composables/use-install-command.spec.ts | 6 +- 20 files changed, 385 insertions(+), 217 deletions(-) create mode 100644 app/composables/usePackageSidebarPreferences.ts delete mode 100644 app/composables/useSettings.ts create mode 100644 app/composables/useUserPreferences.ts create mode 100644 app/composables/useUserPreferencesProvider.ts create mode 100644 app/plugins/preferences-sync.client.ts diff --git a/app/components/CollapsibleSection.vue b/app/components/CollapsibleSection.vue index bf48c9eb0..6addaeac4 100644 --- a/app/components/CollapsibleSection.vue +++ b/app/components/CollapsibleSection.vue @@ -14,7 +14,7 @@ const props = withDefaults(defineProps(), { headingLevel: 'h2', }) -const appSettings = useSettings() +const { sidebarPreferences } = usePackageSidebarPreferences() const buttonId = `${props.id}-collapsible-button` const contentId = `${props.id}-collapsible-content` @@ -23,8 +23,8 @@ const headingId = `${props.id}-heading` const isOpen = shallowRef(true) onPrehydrate(() => { - const settings = JSON.parse(localStorage.getItem('npmx-settings') || '{}') - const collapsed: string[] = settings?.sidebar?.collapsed || [] + const sidebar = JSON.parse(localStorage.getItem('npmx-sidebar-preferences') || '{}') + const collapsed: string[] = sidebar?.collapsed || [] for (const id of collapsed) { if (!document.documentElement.dataset.collapsed?.includes(id)) { document.documentElement.dataset.collapsed = ( @@ -45,17 +45,16 @@ onMounted(() => { function toggle() { isOpen.value = !isOpen.value - const removed = appSettings.settings.value.sidebar.collapsed.filter(c => c !== props.id) + const removed = sidebarPreferences.value.collapsed.filter(c => c !== props.id) if (isOpen.value) { - appSettings.settings.value.sidebar.collapsed = removed + sidebarPreferences.value.collapsed = removed } else { removed.push(props.id) - appSettings.settings.value.sidebar.collapsed = removed + sidebarPreferences.value.collapsed = removed } - document.documentElement.dataset.collapsed = - appSettings.settings.value.sidebar.collapsed.join(' ') + document.documentElement.dataset.collapsed = sidebarPreferences.value.collapsed.join(' ') } const ariaLabel = computed(() => { diff --git a/app/components/Settings/AccentColorPicker.vue b/app/components/Settings/AccentColorPicker.vue index 768976d05..927e87f71 100644 --- a/app/components/Settings/AccentColorPicker.vue +++ b/app/components/Settings/AccentColorPicker.vue @@ -1,11 +1,11 @@ @@ -61,6 +61,30 @@ const setLocale: typeof setNuxti18nLocale = locale => {

{{ $t('settings.tagline') }}

+ + +
+ + + + +
+
@@ -76,23 +100,33 @@ const setLocale: typeof setNuxti18nLocale = locale => { - + + + + @@ -122,7 +156,7 @@ const setLocale: typeof setNuxti18nLocale = locale => { @@ -132,7 +166,7 @@ const setLocale: typeof setNuxti18nLocale = locale => { @@ -142,7 +176,7 @@ const setLocale: typeof setNuxti18nLocale = locale => { diff --git a/app/plugins/i18n-loader.client.ts b/app/plugins/i18n-loader.client.ts index b34894396..81f88ce72 100644 --- a/app/plugins/i18n-loader.client.ts +++ b/app/plugins/i18n-loader.client.ts @@ -1,20 +1,18 @@ export default defineNuxtPlugin({ + name: 'i18n-loader', + dependsOn: ['preferences-sync'], enforce: 'post', env: { islands: false }, setup() { const { $i18n } = useNuxtApp() const { locale, locales, setLocale } = $i18n - const { settings } = useSettings() - const settingsLocale = settings.value.selectedLocale + const { preferences } = useUserPreferences() + const settingsLocale = preferences.value.selectedLocale - if ( - settingsLocale && - // Check if the value is a supported locale - locales.value.map(l => l.code).includes(settingsLocale) && - // Check if the value is not a current locale - settingsLocale !== locale.value - ) { - setLocale(settingsLocale) + const matchedLocale = locales.value.map(l => l.code).find(code => code === settingsLocale) + + if (matchedLocale && matchedLocale !== locale.value) { + setLocale(matchedLocale) } }, }) diff --git a/app/plugins/preferences-sync.client.ts b/app/plugins/preferences-sync.client.ts new file mode 100644 index 000000000..9c71b7c25 --- /dev/null +++ b/app/plugins/preferences-sync.client.ts @@ -0,0 +1,13 @@ +export default defineNuxtPlugin({ + name: 'preferences-sync', + setup() { + const { initSync } = useUserPreferences() + const { applyStoredColorMode } = useColorModePreference() + + // Apply stored color mode preference early (before components mount) + applyStoredColorMode() + + // Initialize server sync for authenticated users + initSync() + }, +}) diff --git a/app/utils/prehydrate.ts b/app/utils/prehydrate.ts index 365d8e0a6..b2c3fc7c6 100644 --- a/app/utils/prehydrate.ts +++ b/app/utils/prehydrate.ts @@ -15,16 +15,16 @@ export function initPreferencesOnPrehydrate() { // Valid package manager IDs const validPMs = new Set(['npm', 'pnpm', 'yarn', 'bun', 'deno', 'vlt']) - // Read settings from localStorage - const settings = JSON.parse(localStorage.getItem('npmx-settings') || '{}') + // Read user preferences from localStorage + const preferences = JSON.parse(localStorage.getItem('npmx-user-preferences') || '{}') - const accentColorId = settings.accentColorId + const accentColorId = preferences.accentColorId if (accentColorId && accentColorIds.has(accentColorId)) { document.documentElement.style.setProperty('--accent-color', `var(--swatch-${accentColorId})`) } // Apply background accent - const preferredBackgroundTheme = settings.preferredBackgroundTheme + const preferredBackgroundTheme = preferences.preferredBackgroundTheme if (preferredBackgroundTheme) { document.documentElement.dataset.bgTheme = preferredBackgroundTheme } @@ -50,6 +50,8 @@ export function initPreferencesOnPrehydrate() { // Set data attribute for CSS-based visibility document.documentElement.dataset.pm = pm - document.documentElement.dataset.collapsed = settings.sidebar?.collapsed?.join(' ') ?? '' + // Read sidebar preferences from separate localStorage key + const sidebar = JSON.parse(localStorage.getItem('npmx-sidebar-preferences') || '{}') + document.documentElement.dataset.collapsed = sidebar.collapsed?.join(' ') ?? '' }) } diff --git a/i18n/locales/en.json b/i18n/locales/en.json index a19c77355..07e92cc74 100644 --- a/i18n/locales/en.json +++ b/i18n/locales/en.json @@ -78,7 +78,11 @@ "accent_colors": "Accent colors", "clear_accent": "Clear accent color", "translation_progress": "Translation progress", - "background_themes": "Background shade" + "background_themes": "Background shade", + "syncing": "Syncing...", + "synced": "Settings synced", + "sync_error": "Sync failed", + "sync_enabled": "Cloud sync enabled" }, "i18n": { "missing_keys": "{count} missing translation | {count} missing translations", diff --git a/lunaria/files/en-GB.json b/lunaria/files/en-GB.json index 10cf973e7..f1852de7a 100644 --- a/lunaria/files/en-GB.json +++ b/lunaria/files/en-GB.json @@ -78,7 +78,11 @@ "accent_colors": "Accent colors", "clear_accent": "Clear accent colour", "translation_progress": "Translation progress", - "background_themes": "Background shade" + "background_themes": "Background shade", + "syncing": "Syncing...", + "synced": "Settings synced", + "sync_error": "Sync failed", + "sync_enabled": "Cloud sync enabled" }, "i18n": { "missing_keys": "{count} missing translation | {count} missing translations", diff --git a/lunaria/files/en-US.json b/lunaria/files/en-US.json index a19c77355..07e92cc74 100644 --- a/lunaria/files/en-US.json +++ b/lunaria/files/en-US.json @@ -78,7 +78,11 @@ "accent_colors": "Accent colors", "clear_accent": "Clear accent color", "translation_progress": "Translation progress", - "background_themes": "Background shade" + "background_themes": "Background shade", + "syncing": "Syncing...", + "synced": "Settings synced", + "sync_error": "Sync failed", + "sync_enabled": "Cloud sync enabled" }, "i18n": { "missing_keys": "{count} missing translation | {count} missing translations", diff --git a/shared/schemas/userPreferences.ts b/shared/schemas/userPreferences.ts index 241016fc8..ef615bff4 100644 --- a/shared/schemas/userPreferences.ts +++ b/shared/schemas/userPreferences.ts @@ -5,6 +5,8 @@ const AccentColorIdSchema = picklist(Object.keys(ACCENT_COLORS.light) as [string const BackgroundThemeIdSchema = picklist(Object.keys(BACKGROUND_THEMES) as [string, ...string[]]) +const ColorModePreferenceSchema = picklist(['light', 'dark', 'system']) + export const UserPreferencesSchema = object({ /** Display dates as relative (e.g., "3 days ago") instead of absolute */ relativeDates: optional(boolean()), @@ -18,6 +20,8 @@ export const UserPreferencesSchema = object({ hidePlatformPackages: optional(boolean()), /** User-selected locale code (e.g., "en", "de", "ja") */ selectedLocale: optional(nullable(string())), + /** Color mode preference: 'light', 'dark', or 'system' */ + colorModePreference: optional(nullable(ColorModePreferenceSchema)), /** Timestamp of last update (ISO 8601) - managed by server */ updatedAt: optional(string()), }) @@ -26,6 +30,7 @@ export type UserPreferences = InferOutput export type AccentColorId = keyof typeof ACCENT_COLORS.light export type BackgroundThemeId = keyof typeof BACKGROUND_THEMES +export type ColorModePreference = 'light' | 'dark' | 'system' /** * Default user preferences. @@ -38,6 +43,7 @@ export const DEFAULT_USER_PREFERENCES: Required ({ +vi.mock('~/composables/useUserPreferences', () => ({ useRelativeDates: () => mockRelativeDates, - useSettings: () => ({ - settings: ref({ relativeDates: mockRelativeDates.value }), + useUserPreferences: () => ({ + preferences: ref({ relativeDates: mockRelativeDates.value }), }), useAccentColor: () => ({}), })) diff --git a/test/nuxt/components/compare/FacetRow.spec.ts b/test/nuxt/components/compare/FacetRow.spec.ts index ff0765793..f570c038b 100644 --- a/test/nuxt/components/compare/FacetRow.spec.ts +++ b/test/nuxt/components/compare/FacetRow.spec.ts @@ -3,10 +3,10 @@ import { mountSuspended } from '@nuxt/test-utils/runtime' import FacetRow from '~/components/Compare/FacetRow.vue' // Mock useRelativeDates for DateTime component -vi.mock('~/composables/useSettings', () => ({ +vi.mock('~/composables/useUserPreferences', () => ({ useRelativeDates: () => ref(false), - useSettings: () => ({ - settings: ref({ relativeDates: false }), + useUserPreferences: () => ({ + preferences: ref({ relativeDates: false }), }), useAccentColor: () => ({}), initAccentOnPrehydrate: () => {}, diff --git a/test/nuxt/composables/use-install-command.spec.ts b/test/nuxt/composables/use-install-command.spec.ts index f9307d9b3..117d7ce28 100644 --- a/test/nuxt/composables/use-install-command.spec.ts +++ b/test/nuxt/composables/use-install-command.spec.ts @@ -217,9 +217,9 @@ describe('useInstallCommand', () => { }) it('should only include main command when @types disabled via settings', () => { - // Get settings and disable includeTypesInInstall directly - const { settings } = useSettings() - settings.value.includeTypesInInstall = false + // Get preferences and disable includeTypesInInstall directly + const { preferences } = useUserPreferences() + preferences.value.includeTypesInInstall = false const { fullInstallCommand, showTypesInInstall } = useInstallCommand( 'express',