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/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/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/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..ef615bff4 --- /dev/null +++ b/shared/schemas/userPreferences.ts @@ -0,0 +1,49 @@ +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[]]) + +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()), + /** 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())), + /** Color mode preference: 'light', 'dark', or 'system' */ + colorModePreference: optional(nullable(ColorModePreferenceSchema)), + /** 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 +export type ColorModePreference = 'light' | 'dark' | 'system' + +/** + * 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, + colorModePreference: null, +} + +export const USER_PREFERENCES_STORAGE_BASE = 'npmx-kv-user-preferences' diff --git a/test/nuxt/components/DateTime.spec.ts b/test/nuxt/components/DateTime.spec.ts index 1ae7c1644..c643c2cec 100644 --- a/test/nuxt/components/DateTime.spec.ts +++ b/test/nuxt/components/DateTime.spec.ts @@ -4,10 +4,10 @@ import DateTime from '~/components/DateTime.vue' // Mock the useRelativeDates composable const mockRelativeDates = shallowRef(false) -vi.mock('~/composables/useSettings', () => ({ +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',