import type { MarketplacePrefs } from '@histoire/shared' import type { InjectionKey } from 'vue' import type { SingleViewportState } from '../components/canvas/single-viewport.js' import type { ContributionPresence } from '../extensions/shell-registry.js' import type { CanvasDefaultArrangement } from './canvas-arrangement.js' import { inject, provide, reactive, ref, watch } from 'vue' import { validateMarketplacePrefs } from '../components/marketplace/shell/marketplace-prefs.js' import { isPluginContributionId } from '../extensions/shell-registry.js' import { marketplaceDefaults } from '../util/marketplace-preferences.js' /** Small storage interface lets standalone persist while embeddings stay memory-only. */ export interface SettingsStorage { /** Reads one local preference. */ getItem: (key: string) => string | null /** Writes one local preference. */ setItem: (key: string, value: string) => void /** Removes overrides after reset. */ removeItem: (key: string) => void } /** Local-only preferences never enter project config patches. */ export interface UiSettings { /** Interface spacing. */ density: 'comfortable' | 'compact' /** Reuse zoom across stories. */ syncZoom: boolean /** Rerun tests after story updates. */ watchTests: boolean /** Browser-local marketplace preferences. */ marketplace: MarketplacePrefs } /** Settings sections, ordered like the supplied design. */ export const SETTINGS_SECTIONS = [ { id: 'general', label: 'General', icon: 'settings' }, { id: 'appearance', label: 'Appearance', icon: 'palette' }, { id: 'viewports', label: 'Viewports', icon: 'monitor' }, { id: 'tests', label: 'Tests', icon: 'flask-conical', devOnly: true }, { id: 'agents', label: 'AI agents (ACP)', icon: 'bot', devOnly: true }, { id: 'mcp', label: 'MCP server', icon: 'plug', devOnly: true }, { id: 'shortcuts', label: 'Keyboard shortcuts', icon: 'keyboard' }, { id: 'plugins', label: 'Plugins', icon: 'puzzle', /** Shared store badge source. */ badge: 'marketplaceUpdates' }, { id: 'about', label: 'About', icon: 'info' }, ] as const /** Registry view of plugin settings sections; see `createContributionLookup`. */ export interface SettingsSectionRegistry { /** Presence of one candidate plugin section id. */ presence: (id: unknown) => ContributionPresence } /** * Hidden dev sections and invalid URLs recover to Appearance. Plugin sections (`:`) * are kept while available or possibly still loading, so deep links survive plugin setup. * @param section Route section parameter. * @param dev Dev builds expose tests, agents and MCP. * @param sections Plugin section registry; without one (no workbench bound yet) plugin * sections are kept for the page to resolve. */ export function normalizeSettingsSection(section: unknown, dev: boolean, sections?: SettingsSectionRegistry): string { if (isPluginContributionId(section)) return !sections || sections.presence(section) !== 'missing' ? section : 'appearance' return SETTINGS_SECTIONS.find(item => item.id === section && (dev || !('devOnly' in item)))?.id ?? 'appearance' } /** Creates one workbench preference owner; no active Pinia/global state. */ export function createUiSettingsStore(options: { storage?: SettingsStorage, warn?: (message: string) => void }) { /** Each reset receives fresh nested values. */ const defaults = (): UiSettings => ({ density: 'comfortable', syncZoom: false, watchTests: false, marketplace: marketplaceDefaults() }) const state = reactive(defaults()) const singleViewport = reactive({ mode: 'responsive' }) const defaultArrange = ref() try { const raw = options.storage?.getItem('_histoire-ui-settings') if (raw) { const saved = JSON.parse(raw) if (!saved || !['comfortable', 'compact'].includes(saved.density) || typeof saved.syncZoom !== 'boolean' || typeof saved.watchTests !== 'boolean') throw new Error('Invalid settings') Object.assign(state, { density: saved.density, syncZoom: saved.syncZoom, watchTests: saved.watchTests, marketplace: validateMarketplacePrefs(saved.marketplace) }) } const arrange = options.storage?.getItem('_histoire-ui-arrange') if (arrange) { const value = JSON.parse(arrange) if (value === 'single' || value === 'grid' || value === 'list') defaultArrange.value = value } } catch { (options.warn ?? console.warn)('Corrupt Histoire UI settings discarded') try { options.storage?.removeItem('_histoire-ui-settings') } catch { /* Denied storage cannot prevent mounting settings. */ } } /** One persistence path also observes nested preference edits and replacement. */ const stop = watch(state, persist, { deep: true, flush: 'sync' }) /** Serialize the owning settings state, including direct marketplace edits. */ function persist(): void { try { options.storage?.setItem('_histoire-ui-settings', JSON.stringify(state)) } catch { /* Memory preferences still apply when storage is unavailable. */ } } /** Apply partial local preferences through the same persistence owner. */ function update(patch: Partial): void { Object.assign(state, patch) } return { /** Release persistence observation with the owning workbench. */ dispose: stop, state, defaultArrange, singleViewport, update, /** Arrangement override is separate from the documented local-only settings shape. */ setArrange(value: CanvasDefaultArrangement | undefined): void { defaultArrange.value = value try { if (value) options.storage?.setItem('_histoire-ui-arrange', JSON.stringify(value)) else options.storage?.removeItem('_histoire-ui-arrange') } catch { /* Runtime does not depend on browser storage availability. */ } }, /** Reset keeps project defaults authoritative. */ reset(): void { update(defaults()) }, } } /** Single nearest-provider owner, absent on reusable embedded surfaces. */ const settingsKey: InjectionKey> = Symbol('histoire-ui-settings') /** Installs standalone-owned preferences beneath its HistoireProvider. */ export function provideUiSettingsStore(store: ReturnType): void { provide(settingsKey, store) } /** Reads only owning workbench preferences. */ export function useUiSettingsStore(): ReturnType | undefined { return inject(settingsKey, undefined) }