diff --git a/package.json b/package.json index ff0006982..ae7a09f01 100644 --- a/package.json +++ b/package.json @@ -120,6 +120,7 @@ "@tanstack/react-router-ssr-query": "1.167.2", "@tanstack/react-start": "1.168.60", "@tanstack/react-start-client": "1.168.39", + "@tanstack/react-store": "^0.11.2", "@tanstack/react-table": "9.0.0", "@tanstack/react-virtual": "^3.14.9", "@tanstack/workflow-core": "0.0.4", @@ -178,8 +179,7 @@ "vite-bundle-analyzer": "^1.3.6", "xstate": "^5.30.0", "yaml": "^2.9.0", - "zod": "^4.3.6", - "zustand": "^5.0.12" + "zod": "^4.3.6" }, "devDependencies": { "@cloudflare/vite-plugin": "^1.62.5", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4b950b924..1e5c23805 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -195,6 +195,9 @@ importers: '@tanstack/react-start-client': specifier: 1.168.39 version: 1.168.39(react-dom@19.2.3(react@19.2.3))(react@19.2.3) + '@tanstack/react-store': + specifier: ^0.11.2 + version: 0.11.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3) '@tanstack/react-table': specifier: 9.0.0 version: 9.0.0(react-dom@19.2.3(react@19.2.3))(react@19.2.3) @@ -372,9 +375,6 @@ importers: zod: specifier: ^4.3.6 version: 4.3.6 - zustand: - specifier: ^5.0.12 - version: 5.0.12(@types/react@19.2.14)(react@19.2.3)(use-sync-external-store@1.6.0(react@19.2.3)) devDependencies: '@cloudflare/vite-plugin': specifier: ^1.62.5 @@ -4408,12 +4408,6 @@ packages: vite: optional: true - '@tanstack/react-store@0.11.0': - resolution: {integrity: sha512-tX4YXh3PDkmpvGQWkWqKpzs/MSqbtuwY9dWdWhtV9Q50PmO+jOkUKIWIX4G85dwt7lxdHLXsiaEKPdKmC8F41w==} - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - '@tanstack/react-store@0.11.2': resolution: {integrity: sha512-oj5O5DmiMWE+ih+SioX2ayC1kbK7d3fpLx0B75fPJr9nY3zU+hoW010yr64qXsY/9fyiLVE2bn5mGNV3owm8RQ==} peerDependencies: @@ -11963,7 +11957,7 @@ snapshots: '@tanstack/react-pacer@0.22.1(react-dom@19.2.3(react@19.2.3))(react@19.2.3)': dependencies: '@tanstack/pacer': 0.21.1 - '@tanstack/react-store': 0.11.0(react-dom@19.2.3(react@19.2.3))(react@19.2.3) + '@tanstack/react-store': 0.11.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3) react: 19.2.3 react-dom: 19.2.3(react@19.2.3) @@ -12082,13 +12076,6 @@ snapshots: - vite-plugin-solid - webpack - '@tanstack/react-store@0.11.0(react-dom@19.2.3(react@19.2.3))(react@19.2.3)': - dependencies: - '@tanstack/store': 0.11.0 - react: 19.2.3 - react-dom: 19.2.3(react@19.2.3) - use-sync-external-store: 1.6.0(react@19.2.3) - '@tanstack/react-store@0.11.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3)': dependencies: '@tanstack/store': 0.11.2 @@ -12098,7 +12085,7 @@ snapshots: '@tanstack/react-table@9.0.0(react-dom@19.2.3(react@19.2.3))(react@19.2.3)': dependencies: - '@tanstack/react-store': 0.11.0(react-dom@19.2.3(react@19.2.3))(react@19.2.3) + '@tanstack/react-store': 0.11.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3) '@tanstack/table-core': 9.0.0 react: 19.2.3 transitivePeerDependencies: @@ -12254,7 +12241,7 @@ snapshots: '@tanstack/table-core@9.0.0': dependencies: - '@tanstack/store': 0.11.0 + '@tanstack/store': 0.11.2 '@tanstack/virtual-core@3.17.7': {} diff --git a/src/components/Doc.tsx b/src/components/Doc.tsx index 0a75bb9a9..65627c2ee 100644 --- a/src/components/Doc.tsx +++ b/src/components/Doc.tsx @@ -86,12 +86,9 @@ export function Doc({ const localCurrentFramework = useLocalCurrentFramework() const currentFramework = React.useMemo(() => { const fw = - frameworkProp || - paramsFramework || - localCurrentFramework.currentFramework || - 'react' + frameworkProp || paramsFramework || localCurrentFramework || 'react' return typeof fw === 'string' ? fw.toLowerCase() : fw - }, [frameworkProp, paramsFramework, localCurrentFramework.currentFramework]) + }, [frameworkProp, paramsFramework, localCurrentFramework]) const isTocVisible = shouldRenderToc && headings.length > 1 diff --git a/src/components/FrameworkSelect.tsx b/src/components/FrameworkSelect.tsx index 2d4e577e4..0a8c398c0 100644 --- a/src/components/FrameworkSelect.tsx +++ b/src/components/FrameworkSelect.tsx @@ -1,5 +1,5 @@ import * as React from 'react' -import { create } from 'zustand' +import { createStore, useSelector } from '@tanstack/react-store' import { useNavigate, useParams } from '@tanstack/react-router' import { useQueryClient } from '@tanstack/react-query' import { Select } from './Select' @@ -48,19 +48,22 @@ export function FrameworkSelect({ libraryId }: { libraryId: LibraryId }) { ) } -// Let's use zustand to wrap the local storage logic. This way +// Let's use TanStack Store to wrap the local storage logic. This way // we'll get subscriptions for free and we can use it in other // components if we need to. -export const useLocalCurrentFramework = create<{ - currentFramework?: string - setCurrentFramework: (framework: string) => void -}>((set) => ({ - currentFramework: getLocalStorageItem('framework') || undefined, - setCurrentFramework: (framework: string) => { - setLocalStorageItem('framework', framework) - set({ currentFramework: framework }) - }, -})) +export const localCurrentFrameworkStore = createStore( + { currentFramework: getLocalStorageItem('framework') || undefined }, + ({ setState }) => ({ + setCurrentFramework: (framework: string) => { + setLocalStorageItem('framework', framework) + setState(() => ({ currentFramework: framework })) + }, + }), +) + +export function useLocalCurrentFramework() { + return useSelector(localCurrentFrameworkStore, (s) => s.currentFramework) +} /** * Get the stored framework preference from localStorage. @@ -77,12 +80,11 @@ export function getStoredFrameworkPreference(): string | undefined { export function usePersistFrameworkPreference() { const userQuery = useCurrentUserQuery() const queryClient = useQueryClient() - const localCurrentFramework = useLocalCurrentFramework() return React.useCallback( (framework: string) => { // Always update localStorage as fallback - localCurrentFramework.setCurrentFramework(framework) + localCurrentFrameworkStore.actions.setCurrentFramework(framework) queryClient.setQueryData(currentUserQueryOptions.queryKey, (user) => user ? { ...user, lastUsedFramework: framework } : user, ) @@ -91,7 +93,7 @@ export function usePersistFrameworkPreference() { persistFrameworkToServer(framework) } }, - [localCurrentFramework, queryClient, userQuery.data], + [queryClient, userQuery.data], ) } @@ -130,12 +132,13 @@ export function useCurrentFramework(frameworks: Framework[]) { }) const localCurrentFramework = useLocalCurrentFramework() + const { setCurrentFramework } = localCurrentFrameworkStore.actions // Priority: URL params > DB (logged-in) > localStorage > 'react' const userFramework = userQuery.data?.lastUsedFramework let framework = (paramsFramework || userFramework || - localCurrentFramework.currentFramework || + localCurrentFramework || 'react') as Framework framework = frameworks.includes(framework) ? framework : 'react' @@ -146,7 +149,7 @@ export function useCurrentFramework(frameworks: Framework[]) { params: { framework } as any, }) // Always update localStorage as fallback - localCurrentFramework.setCurrentFramework(framework) + setCurrentFramework(framework) queryClient.setQueryData(currentUserQueryOptions.queryKey, (user) => user ? { ...user, lastUsedFramework: framework } : user, ) @@ -156,21 +159,18 @@ export function useCurrentFramework(frameworks: Framework[]) { persistFrameworkToServer(framework) } }, - [localCurrentFramework, navigate, queryClient, userQuery.data], + [navigate, queryClient, userQuery.data, setCurrentFramework], ) React.useEffect(() => { // Set the framework in localStorage if it doesn't exist - if (!localCurrentFramework.currentFramework) { - localCurrentFramework.setCurrentFramework(framework) + if (!localCurrentFramework) { + setCurrentFramework(framework) } // Set the framework in localStorage if it doesn't match the URL - if ( - paramsFramework && - paramsFramework !== localCurrentFramework.currentFramework - ) { - localCurrentFramework.setCurrentFramework(paramsFramework) + if (paramsFramework && paramsFramework !== localCurrentFramework) { + setCurrentFramework(paramsFramework) } }) diff --git a/src/components/NavbarCartButton.tsx b/src/components/NavbarCartButton.tsx index 22c3e6d9a..a5bd1347f 100644 --- a/src/components/NavbarCartButton.tsx +++ b/src/components/NavbarCartButton.tsx @@ -2,7 +2,7 @@ import { Link, useLocation } from '@tanstack/react-router' import { ShoppingCartIcon } from '@phosphor-icons/react/ShoppingCart' import { twMerge } from 'tailwind-merge' import { useCart } from '~/hooks/useCart' -import { useCartDrawerStore } from '~/components/shop/cartDrawerStore' +import { cartDrawerStore } from '~/components/shop/cartDrawerStore' const badgeClasses = twMerge( 'absolute -top-1 -right-1 min-w-[1.125rem] h-[1.125rem] px-1', @@ -34,7 +34,7 @@ const buttonClasses = twMerge( export function NavbarCartButton() { const { pathname } = useLocation() const { totalQuantity } = useCart() - const openDrawer = useCartDrawerStore((s) => s.openDrawer) + const { openDrawer } = cartDrawerStore.actions const onShopRoute = pathname === '/shop' || pathname.startsWith('/shop/') if (!onShopRoute && totalQuantity === 0) return null diff --git a/src/components/VersionSelect.tsx b/src/components/VersionSelect.tsx index e92aa3410..5be2afc3f 100644 --- a/src/components/VersionSelect.tsx +++ b/src/components/VersionSelect.tsx @@ -1,5 +1,5 @@ import * as React from 'react' -import { create } from 'zustand' +import { createStore, useSelector } from '@tanstack/react-store' import { useNavigate, useParams } from '@tanstack/react-router' import { TagIcon } from '@phosphor-icons/react/Tag' import { Select, SelectOption } from './Select' @@ -26,19 +26,18 @@ export function VersionSelect({ libraryId }: { libraryId: LibraryId }) { ) } -// Let's use zustand to wrap the local storage logic. This way +// Let's use TanStack Store to wrap the local storage logic. This way // we'll get subscriptions for free and we can use it in other // components if we need to. -const useLocalCurrentVersion = create<{ - currentVersion?: string - setCurrentVersion: (version: string) => void -}>((set) => ({ - currentVersion: getLocalStorageItem('version') || undefined, - setCurrentVersion: (version: string) => { - setLocalStorageItem('version', version) - set({ currentVersion: version }) - }, -})) +const localCurrentVersionStore = createStore( + { currentVersion: getLocalStorageItem('version') || undefined }, + ({ setState }) => ({ + setCurrentVersion: (version: string) => { + setLocalStorageItem('version', version) + setState(() => ({ currentVersion: version })) + }, + }), +) /** * Use framework in URL path @@ -52,9 +51,13 @@ function useCurrentVersion(versions: string[]) { strict: false, }) - const localCurrentVersion = useLocalCurrentVersion() + const localCurrentVersion = useSelector( + localCurrentVersionStore, + (s) => s.currentVersion, + ) + const { setCurrentVersion } = localCurrentVersionStore.actions - let version = paramsVersion || localCurrentVersion.currentVersion || 'latest' + let version = paramsVersion || localCurrentVersion || 'latest' version = versions.includes(version) ? version : 'latest' @@ -63,20 +66,20 @@ function useCurrentVersion(versions: string[]) { navigate({ params: { version } as never, }) - localCurrentVersion.setCurrentVersion(version) + setCurrentVersion(version) }, - [localCurrentVersion, navigate], + [navigate, setCurrentVersion], ) React.useEffect(() => { // Set the version in localStorage if it doesn't exist - if (!localCurrentVersion.currentVersion) { - localCurrentVersion.setCurrentVersion(version) + if (!localCurrentVersion) { + setCurrentVersion(version) } // Set the version in localStorage if it doesn't match the URL - if (paramsVersion && paramsVersion !== localCurrentVersion.currentVersion) { - localCurrentVersion.setCurrentVersion(paramsVersion) + if (paramsVersion && paramsVersion !== localCurrentVersion) { + setCurrentVersion(paramsVersion) } }) diff --git a/src/components/application-starter/ApplicationStarterProvider.tsx b/src/components/application-starter/ApplicationStarterProvider.tsx index 2c8bc651e..e5890446b 100644 --- a/src/components/application-starter/ApplicationStarterProvider.tsx +++ b/src/components/application-starter/ApplicationStarterProvider.tsx @@ -5,6 +5,7 @@ * Uses proper theme support. */ +import { useSelector } from '@tanstack/react-store' import { createContext, useEffect, @@ -13,7 +14,7 @@ import { type ReactNode, } from 'react' import { useSearch } from '@tanstack/react-router' -import { useApplicationStarterStore } from './store' +import { applicationStarterStore } from './store' import { normalizeFrameworkId } from '~/application-starter/frameworks' interface ApplicationStarterContextValue { @@ -33,8 +34,11 @@ export function ApplicationStarterProvider({ }: ApplicationStarterProviderProps) { const [ready, setReady] = useState(false) const search = useSearch({ strict: false }) as { framework?: string } - const loadFeatures = useApplicationStarterStore((s) => s.loadFeatures) - const featuresLoaded = useApplicationStarterStore((s) => s.featuresLoaded) + const loadFeatures = applicationStarterStore.actions.loadFeatures + const featuresLoaded = useSelector( + applicationStarterStore, + (s) => s.featuresLoaded, + ) const initializedRef = useRef(false) // Set framework from URL before loading features (only once on mount) @@ -44,9 +48,10 @@ export function ApplicationStarterProvider({ // Set framework directly in store without triggering loadFeatures if (search.framework) { - useApplicationStarterStore.setState({ + applicationStarterStore.setState((prev) => ({ + ...prev, framework: normalizeFrameworkId(search.framework), - }) + })) } loadFeatures() }, [loadFeatures, search.framework]) diff --git a/src/components/application-starter/ApplicationStarterWorkspace.tsx b/src/components/application-starter/ApplicationStarterWorkspace.tsx index 1d5da6fbf..6c084adf9 100644 --- a/src/components/application-starter/ApplicationStarterWorkspace.tsx +++ b/src/components/application-starter/ApplicationStarterWorkspace.tsx @@ -1,6 +1,7 @@ +import { useSelector } from '@tanstack/react-store' import { useCallback, useMemo, useState } from 'react' import { QuestionIcon, XIcon } from '@phosphor-icons/react' -import { useApplicationStarterStore } from './store' +import { applicationStarterStore } from './store' import { useApplicationStarterUrl } from './useApplicationStarterUrl' import { ApplicationStarterSummaryPanel, @@ -23,22 +24,35 @@ export function ApplicationStarterWorkspace() { useState(false) const [latestStarterResult, setLatestStarterResult] = useState(null) - const features = useApplicationStarterStore((state) => state.features) - const featureOptions = useApplicationStarterStore( + const features = useSelector( + applicationStarterStore, + (state) => state.features, + ) + const featureOptions = useSelector( + applicationStarterStore, (state) => state.featureOptions, ) - const framework = useApplicationStarterStore((state) => state.framework) - const packageManager = useApplicationStarterStore( + const framework = useSelector( + applicationStarterStore, + (state) => state.framework, + ) + const packageManager = useSelector( + applicationStarterStore, (state) => state.packageManager, ) - const projectName = useApplicationStarterStore((state) => state.projectName) - const selectedTemplate = useApplicationStarterStore( + const projectName = useSelector( + applicationStarterStore, + (state) => state.projectName, + ) + const selectedTemplate = useSelector( + applicationStarterStore, (state) => state.selectedTemplate, ) - const tailwind = useApplicationStarterStore((state) => state.tailwind) - const applyStarterRecipe = useApplicationStarterStore( - (state) => state.applyStarterRecipe, + const tailwind = useSelector( + applicationStarterStore, + (state) => state.tailwind, ) + const applyStarterRecipe = applicationStarterStore.actions.applyStarterRecipe const summary = useApplicationStarterSummaryData() const { notify } = useToast() const displayedSummary = useMemo( @@ -111,7 +125,7 @@ export function ApplicationStarterWorkspace() { await applyStarterRecipe(result.recipe) setLastGeneratedApplicationStarterSignature( createApplicationStarterSignatureFromStore( - useApplicationStarterStore.getState(), + applicationStarterStore.state, ), ) setIsPromptDirtySinceGenerate(false) @@ -244,7 +258,7 @@ function createApplicationStarterSignature({ } function createApplicationStarterSignatureFromStore( - state: ReturnType, + state: typeof applicationStarterStore.state, ) { return createApplicationStarterSignature({ featureOptions: state.featureOptions, diff --git a/src/components/application-starter/CustomTemplateDialog.tsx b/src/components/application-starter/CustomTemplateDialog.tsx index 946974091..5f45d0dea 100644 --- a/src/components/application-starter/CustomTemplateDialog.tsx +++ b/src/components/application-starter/CustomTemplateDialog.tsx @@ -14,7 +14,7 @@ import { XIcon, QuestionIcon, } from '@phosphor-icons/react' -import { useApplicationStarterStore, useCustomTemplate } from './store' +import { applicationStarterStore, useCustomTemplate } from './store' import type { CustomTemplateCompiled } from '~/application-starter/api' interface CustomTemplateDialogProps { @@ -27,9 +27,7 @@ export function CustomTemplateDialog({ onClose }: CustomTemplateDialogProps) { const [error, setError] = useState(null) const [preview, setPreview] = useState(null) - const setCustomTemplate = useApplicationStarterStore( - (s) => s.setCustomTemplate, - ) + const setCustomTemplate = applicationStarterStore.actions.setCustomTemplate const handleLoad = async () => { if (!url.trim()) { @@ -180,9 +178,7 @@ export function CustomTemplateDialog({ onClose }: CustomTemplateDialogProps) { export function CustomTemplateSection() { const [isOpen, setIsOpen] = useState(false) const customTemplate = useCustomTemplate() - const setCustomTemplate = useApplicationStarterStore( - (s) => s.setCustomTemplate, - ) + const setCustomTemplate = applicationStarterStore.actions.setCustomTemplate if (customTemplate) { return ( @@ -261,9 +257,7 @@ export function CustomTemplateItem({ onToggle: () => void }) { const customTemplate = useCustomTemplate() - const setCustomTemplate = useApplicationStarterStore( - (s) => s.setCustomTemplate, - ) + const setCustomTemplate = applicationStarterStore.actions.setCustomTemplate if (customTemplate) { return ( diff --git a/src/components/application-starter/FeaturePicker.tsx b/src/components/application-starter/FeaturePicker.tsx index 542dc6c2f..66eb5bf2f 100644 --- a/src/components/application-starter/FeaturePicker.tsx +++ b/src/components/application-starter/FeaturePicker.tsx @@ -8,6 +8,7 @@ * Partner features use the shared partner placement policy within categories. */ +import { useSelector } from '@tanstack/react-store' import { useState, useMemo } from 'react' import { twMerge } from 'tailwind-merge' import { @@ -19,7 +20,7 @@ import { } from '@phosphor-icons/react' import { matchSorter } from 'match-sorter' import { - useApplicationStarterStore, + applicationStarterStore, useFeatureState, useAvailableFeatures, useAvailableExamples, @@ -371,8 +372,8 @@ interface FeatureCardProps { } function FeatureCard({ feature, categoryColor }: FeatureCardProps) { - const toggleFeature = useApplicationStarterStore((s) => s.toggleFeature) - const getFeatureInfo = useApplicationStarterStore((s) => s.getFeatureInfo) + const toggleFeature = applicationStarterStore.actions.toggleFeature + const getFeatureInfo = applicationStarterStore.actions.getFeatureInfo const { selected, enabled, disabledReason, exclusiveConflict, requiredBy } = useFeatureState(feature.id) @@ -488,9 +489,14 @@ interface FeatureOptionsProps { } export function FeatureOptions({ featureId }: FeatureOptionsProps) { - const feature = useApplicationStarterStore((s) => s.getFeatureInfo(featureId)) - const featureOptions = useApplicationStarterStore((s) => s.featureOptions) - const setFeatureOption = useApplicationStarterStore((s) => s.setFeatureOption) + const feature = useSelector(applicationStarterStore, (s) => + s.availableFeatures.find((f) => f.id === featureId), + ) + const featureOptions = useSelector( + applicationStarterStore, + (s) => s.featureOptions, + ) + const setFeatureOption = applicationStarterStore.actions.setFeatureOption if (!feature || !feature.options || feature.options.length === 0) { return null @@ -562,7 +568,7 @@ export function FeatureOptions({ featureId }: FeatureOptionsProps) { function ExamplePicker() { const examples = useAvailableExamples() const selectedExample = useSelectedExample() - const selectExample = useApplicationStarterStore((s) => s.selectExample) + const selectExample = applicationStarterStore.actions.selectExample const [isOpen, setIsOpen] = useState(true) if (examples.length === 0) return null diff --git a/src/components/application-starter/index.ts b/src/components/application-starter/index.ts index bd80aad0d..4c572fbcd 100644 --- a/src/components/application-starter/index.ts +++ b/src/components/application-starter/index.ts @@ -7,7 +7,7 @@ export { ApplicationStarterProvider } from './ApplicationStarterProvider' export { FeaturePicker, FeatureOptions } from './FeaturePicker' export { - useApplicationStarterStore, + applicationStarterStore, useProjectName, useFeatures, useAvailableFeatures, diff --git a/src/components/application-starter/store.ts b/src/components/application-starter/store.ts index 034ee0230..c7757b1a3 100644 --- a/src/components/application-starter/store.ts +++ b/src/components/application-starter/store.ts @@ -1,12 +1,11 @@ /** * ApplicationStarter Store (v2) * - * Local state management for the new applicationStarter using Zustand. + * Local state management for the new applicationStarter using TanStack Store. * No external CTA dependencies. */ -import { create } from 'zustand' -import { subscribeWithSelector } from 'zustand/middleware' +import { createStore, useSelector } from '@tanstack/react-store' import type { FeatureId, FeatureInfo, @@ -24,7 +23,7 @@ import { TEMPLATES } from '~/application-starter/templates' type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun' -interface ApplicationStarterState { +type ApplicationStarterState = { // Project configuration projectName: string framework: FrameworkId @@ -54,415 +53,407 @@ interface ApplicationStarterState { // UI state integrationSearch: string - - // Actions - setProjectName: (name: string) => void - setFramework: (framework: FrameworkId) => void - setTailwind: (enabled: boolean) => void - toggleFeature: (id: FeatureId) => void - setFeatureOption: ( - featureId: FeatureId, - optionKey: string, - value: unknown, - ) => void - setFeatures: (features: Array) => void - selectExample: (id: FeatureId | null) => void - setPackageManager: (pm: PackageManager) => void - setSkipInstall: (skip: boolean) => void - setSkipGit: (skip: boolean) => void - addCustomIntegration: (integration: IntegrationCompiled) => void - removeCustomIntegration: (id: string) => void - setCustomTemplate: (template: CustomTemplateCompiled | null) => void - setIntegrationSearch: (search: string) => void - setTemplate: (id: string | null) => void - applyStarterRecipe: (recipe: ApplicationStarterRecipe) => Promise - loadFeatures: () => Promise - reset: () => void - - // Derived state helpers - hasFeature: (id: FeatureId) => boolean - getFeatureInfo: (id: FeatureId) => FeatureInfo | undefined - getExampleInfo: (id: FeatureId) => FeatureInfo | undefined - getDefinition: () => ProjectDefinition - isFeatureLockedByExample: (id: FeatureId) => boolean } -const initialState = { +const initialState: ApplicationStarterState = { projectName: 'my-tanstack-app', - framework: 'react' as FrameworkId, + framework: 'react', tailwind: true, - features: [] as Array, - featureOptions: {} as Record>, - selectedExample: null as FeatureId | null, - selectedTemplate: 'blank' as string | null, - packageManager: 'pnpm' as PackageManager, + features: [], + featureOptions: {}, + selectedExample: null, + selectedTemplate: 'blank', + packageManager: 'pnpm', skipInstall: false, skipGit: false, - customIntegrations: [] as Array, - customTemplate: null as CustomTemplateCompiled | null, - availableFeatures: [] as Array, - availableExamples: [] as Array, + customIntegrations: [], + customTemplate: null, + availableFeatures: [], + availableExamples: [], integrationSearch: '', featuresLoaded: false, } -export const useApplicationStarterStore = create()( - subscribeWithSelector((set, get) => ({ - ...initialState, - - setProjectName: (name) => set({ projectName: name }), - - setFramework: (framework) => { - set({ - framework, - features: [], - featureOptions: {}, - selectedExample: null, - selectedTemplate: 'blank', - availableFeatures: [], - availableExamples: [], - featuresLoaded: false, - }) - get().loadFeatures() - }, - - setTailwind: (enabled) => { - const { features, availableFeatures } = get() - if (!enabled) { - const filtered = features.filter((id) => { - const feature = availableFeatures.find((f) => f.id === id) - return !feature?.requiresTailwind +export const applicationStarterStore = createStore( + initialState, + ({ setState, get }) => { + const set = (partial: Partial) => + setState((prev) => ({ ...prev, ...partial })) + + const actions = { + setProjectName: (name: string) => set({ projectName: name }), + + setFramework: (framework: FrameworkId): void => { + set({ + framework, + features: [], + featureOptions: {}, + selectedExample: null, + selectedTemplate: 'blank', + availableFeatures: [], + availableExamples: [], + featuresLoaded: false, }) - set({ tailwind: enabled, features: filtered }) - } else { - set({ tailwind: enabled }) - } - }, - - toggleFeature: (id) => { - const { - features, - availableFeatures, - selectedExample, - availableExamples, - } = get() - - // Check if this feature is locked by selected example - if (selectedExample) { - const example = availableExamples.find((e) => e.id === selectedExample) - if (example?.requires.includes(id)) { - return // Can't toggle features locked by example + actions.loadFeatures() + }, + + setTailwind: (enabled: boolean) => { + const { features, availableFeatures } = get() + if (!enabled) { + const filtered = features.filter((id) => { + const feature = availableFeatures.find((f) => f.id === id) + return !feature?.requiresTailwind + }) + set({ tailwind: enabled, features: filtered }) + } else { + set({ tailwind: enabled }) + } + }, + + toggleFeature: (id: FeatureId) => { + const { + features, + availableFeatures, + selectedExample, + availableExamples, + } = get() + + // Check if this feature is locked by selected example + if (selectedExample) { + const example = availableExamples.find( + (e) => e.id === selectedExample, + ) + if (example?.requires.includes(id)) { + return // Can't toggle features locked by example + } } - } - const isSelected = features.includes(id) + const isSelected = features.includes(id) - if (isSelected) { - const toRemove = new Set([id]) - for (const f of availableFeatures) { - if (f.requires.includes(id) && features.includes(f.id)) { - toRemove.add(f.id) + if (isSelected) { + const toRemove = new Set([id]) + for (const f of availableFeatures) { + if (f.requires.includes(id) && features.includes(f.id)) { + toRemove.add(f.id) + } } - } - set({ features: features.filter((f) => !toRemove.has(f)) }) - } else { - const feature = availableFeatures.find((f) => f.id === id) - if (!feature) return - - const exclusiveConflicts = new Set() - if (feature.exclusive.length > 0) { - for (const existingId of features) { - const existing = availableFeatures.find((f) => f.id === existingId) - if ( - existing?.exclusive.some((e) => feature.exclusive.includes(e)) - ) { - exclusiveConflicts.add(existingId) + set({ features: features.filter((f) => !toRemove.has(f)) }) + } else { + const feature = availableFeatures.find((f) => f.id === id) + if (!feature) return + + const exclusiveConflicts = new Set() + if (feature.exclusive.length > 0) { + for (const existingId of features) { + const existing = availableFeatures.find( + (f) => f.id === existingId, + ) + if ( + existing?.exclusive.some((e) => feature.exclusive.includes(e)) + ) { + exclusiveConflicts.add(existingId) + } } } - } - if (exclusiveConflicts.size > 0) { - const withoutConflicts = features.filter( - (f) => !exclusiveConflicts.has(f), - ) - set({ - features: [...withoutConflicts, ...feature.requires, id], - }) - } else { - const newFeatures = new Set([...features, ...feature.requires, id]) - set({ features: Array.from(newFeatures) }) - } - } - }, - - setFeatureOption: (featureId, optionKey, value) => { - const { featureOptions } = get() - set({ - featureOptions: { - ...featureOptions, - [featureId]: { - ...featureOptions[featureId], - [optionKey]: value, - }, - }, - }) - }, - - setFeatures: (features) => set({ features }), - - selectExample: (id) => { - const { availableExamples, features } = get() - - if (id === null) { - // Deselecting example - remove its locked dependencies from features - const currentExample = get().selectedExample - if (currentExample) { - const example = availableExamples.find((e) => e.id === currentExample) - if (example) { - const lockedFeatures = new Set(example.requires) + if (exclusiveConflicts.size > 0) { + const withoutConflicts = features.filter( + (f) => !exclusiveConflicts.has(f), + ) set({ - selectedExample: null, - features: features.filter((f) => !lockedFeatures.has(f)), + features: [...withoutConflicts, ...feature.requires, id], }) - return + } else { + const newFeatures = new Set([...features, ...feature.requires, id]) + set({ features: Array.from(newFeatures) }) } } - set({ selectedExample: null }) - return - } - - const example = availableExamples.find((e) => e.id === id) - if (!example) return - - // Add example's required features (locked) - const newFeatures = new Set([...features, ...example.requires]) - - set({ - selectedExample: id, - features: Array.from(newFeatures), - }) - }, - - setPackageManager: (pm) => set({ packageManager: pm }), - setSkipInstall: (skip) => set({ skipInstall: skip }), - setSkipGit: (skip) => set({ skipGit: skip }), - - addCustomIntegration: (integration) => { - const { customIntegrations, features, availableFeatures } = get() - if (customIntegrations.some((i) => i.id === integration.id)) return - - const featureInfo: FeatureInfo = { - id: integration.id, - name: integration.name, - description: integration.description, - category: 'other', - requires: integration.dependsOn ?? [], - exclusive: [], - hasOptions: !!integration.options, - link: integration.link, - color: '#8B5CF6', - requiresTailwind: integration.tailwind === false ? true : undefined, - } - - set({ - customIntegrations: [...customIntegrations, integration], - availableFeatures: [...availableFeatures, featureInfo], - features: [...features, integration.id], - }) - }, - - removeCustomIntegration: (id) => { - const { customIntegrations, features, availableFeatures } = get() - set({ - customIntegrations: customIntegrations.filter((i) => i.id !== id), - availableFeatures: availableFeatures.filter((f) => f.id !== id), - features: features.filter((f) => f !== id), - }) - }, - - setCustomTemplate: (template) => { - set({ customTemplate: template }) - }, - - setIntegrationSearch: (search) => { - set({ integrationSearch: search }) - }, - - setTemplate: (id) => { - const template = TEMPLATES.find((t) => t.id === id) - if (!template) return - - const { availableFeatures, availableExamples } = get() - - // Filter to only features that exist in current framework - const validFeatures = template.features.filter((f) => - availableFeatures.some((af) => af.id === f), - ) - - const example = template.exampleId - ? availableExamples.find((e) => e.id === template.exampleId) - : undefined - const exampleLockedFeatures = example?.requires ?? [] - const featuresWithExampleDeps = Array.from( - new Set([...validFeatures, ...exampleLockedFeatures]), - ).filter((f) => availableFeatures.some((af) => af.id === f)) - - set({ - selectedTemplate: id, - features: featuresWithExampleDeps, - featureOptions: {}, - selectedExample: example?.id ?? null, - }) - }, - - applyStarterRecipe: async (recipe) => { - if (get().framework !== recipe.framework) { + }, + + setFeatureOption: ( + featureId: FeatureId, + optionKey: string, + value: unknown, + ) => { + const { featureOptions } = get() set({ - framework: recipe.framework, - features: [], + featureOptions: { + ...featureOptions, + [featureId]: { + ...featureOptions[featureId], + [optionKey]: value, + }, + }, + }) + }, + + setFeatures: (features: Array) => set({ features }), + + selectExample: (id: FeatureId | null) => { + const { availableExamples, features } = get() + + if (id === null) { + // Deselecting example - remove its locked dependencies from features + const currentExample = get().selectedExample + if (currentExample) { + const example = availableExamples.find( + (e) => e.id === currentExample, + ) + if (example) { + const lockedFeatures = new Set(example.requires) + set({ + selectedExample: null, + features: features.filter((f) => !lockedFeatures.has(f)), + }) + return + } + } + set({ selectedExample: null }) + return + } + + const example = availableExamples.find((e) => e.id === id) + if (!example) return + + // Add example's required features (locked) + const newFeatures = new Set([...features, ...example.requires]) + + set({ + selectedExample: id, + features: Array.from(newFeatures), + }) + }, + + setPackageManager: (pm: PackageManager) => set({ packageManager: pm }), + setSkipInstall: (skip: boolean) => set({ skipInstall: skip }), + setSkipGit: (skip: boolean) => set({ skipGit: skip }), + + addCustomIntegration: (integration: IntegrationCompiled) => { + const { customIntegrations, features, availableFeatures } = get() + if (customIntegrations.some((i) => i.id === integration.id)) return + + const featureInfo: FeatureInfo = { + id: integration.id, + name: integration.name, + description: integration.description, + category: 'other', + requires: integration.dependsOn ?? [], + exclusive: [], + hasOptions: !!integration.options, + link: integration.link, + color: '#8B5CF6', + requiresTailwind: integration.tailwind === false ? true : undefined, + } + + set({ + customIntegrations: [...customIntegrations, integration], + availableFeatures: [...availableFeatures, featureInfo], + features: [...features, integration.id], + }) + }, + + removeCustomIntegration: (id: string) => { + const { customIntegrations, features, availableFeatures } = get() + set({ + customIntegrations: customIntegrations.filter((i) => i.id !== id), + availableFeatures: availableFeatures.filter((f) => f.id !== id), + features: features.filter((f) => f !== id), + }) + }, + + setCustomTemplate: (template: CustomTemplateCompiled | null) => { + set({ customTemplate: template }) + }, + + setIntegrationSearch: (search: string) => { + set({ integrationSearch: search }) + }, + + setTemplate: (id: string | null) => { + const template = TEMPLATES.find((t) => t.id === id) + if (!template) return + + const { availableFeatures, availableExamples } = get() + + // Filter to only features that exist in current framework + const validFeatures = template.features.filter((f) => + availableFeatures.some((af) => af.id === f), + ) + + const example = template.exampleId + ? availableExamples.find((e) => e.id === template.exampleId) + : undefined + const exampleLockedFeatures = example?.requires ?? [] + const featuresWithExampleDeps = Array.from( + new Set([...validFeatures, ...exampleLockedFeatures]), + ).filter((f) => availableFeatures.some((af) => af.id === f)) + + set({ + selectedTemplate: id, + features: featuresWithExampleDeps, featureOptions: {}, - selectedExample: null, - selectedTemplate: 'blank', - availableFeatures: [], - availableExamples: [], - featuresLoaded: false, + selectedExample: example?.id ?? null, }) - await get().loadFeatures() - } else if (!get().featuresLoaded) { - await get().loadFeatures() - } - - const { availableFeatures, availableExamples, projectName } = get() - const validFeatures = getRecipeApplicationStarterFeatures(recipe).filter( - (featureId) => - availableFeatures.some((feature) => feature.id === featureId), - ) - - const recipeTemplateIsExample = isCliTemplateId(recipe.template) - const exampleLockedFeatures = recipeTemplateIsExample - ? (availableExamples.find((e) => e.id === recipe.template)?.requires ?? - []) - : [] - - // featureOptions are valid for any add-on the project will end up with — - // either explicitly chosen features or those locked by the selected example. - const optionEligibleFeatures = new Set([ - ...validFeatures, - ...exampleLockedFeatures, - ]) - const nextFeatureOptions = Object.fromEntries( - Object.entries(recipe.featureOptions).filter(([featureId]) => - optionEligibleFeatures.has(featureId), - ), - ) - - set({ - projectName: recipe.projectName ?? projectName, - tailwind: recipe.tailwind, - features: validFeatures, - featureOptions: nextFeatureOptions, - selectedExample: recipeTemplateIsExample ? recipe.template! : null, - selectedTemplate: recipeTemplateIsExample - ? null - : (recipe.template ?? null), - packageManager: recipe.packageManager, - skipInstall: false, - skipGit: false, - }) - }, - - loadFeatures: async () => { - try { - if (import.meta.env.SSR) { - throw new Error( - 'Application Starter features are only loaded in the browser', - ) + }, + + applyStarterRecipe: async ( + recipe: ApplicationStarterRecipe, + ): Promise => { + if (get().framework !== recipe.framework) { + set({ + framework: recipe.framework, + features: [], + featureOptions: {}, + selectedExample: null, + selectedTemplate: 'blank', + availableFeatures: [], + availableExamples: [], + featuresLoaded: false, + }) + await actions.loadFeatures() + } else if (!get().featuresLoaded) { + await actions.loadFeatures() } - const { framework } = get() - const { getFeaturesHandler } = - await import('~/application-starter/api/features') - const data = await getFeaturesHandler(framework) + const { availableFeatures, availableExamples, projectName } = get() + const validFeatures = getRecipeApplicationStarterFeatures( + recipe, + ).filter((featureId) => + availableFeatures.some((feature) => feature.id === featureId), + ) + + const recipeTemplateIsExample = isCliTemplateId(recipe.template) + const exampleLockedFeatures = recipeTemplateIsExample + ? (availableExamples.find((e) => e.id === recipe.template) + ?.requires ?? []) + : [] + + // featureOptions are valid for any add-on the project will end up with — + // either explicitly chosen features or those locked by the selected example. + const optionEligibleFeatures = new Set([ + ...validFeatures, + ...exampleLockedFeatures, + ]) + const nextFeatureOptions = Object.fromEntries( + Object.entries(recipe.featureOptions).filter(([featureId]) => + optionEligibleFeatures.has(featureId), + ), + ) + set({ - availableFeatures: data.features, - availableExamples: data.examples || [], - featuresLoaded: true, + projectName: recipe.projectName ?? projectName, + tailwind: recipe.tailwind, + features: validFeatures, + featureOptions: nextFeatureOptions, + selectedExample: recipeTemplateIsExample ? recipe.template! : null, + selectedTemplate: recipeTemplateIsExample + ? null + : (recipe.template ?? null), + packageManager: recipe.packageManager, + skipInstall: false, + skipGit: false, }) - // Apply blank template after features load to set default features - get().setTemplate('blank') - } catch (error) { - console.error('Failed to load features:', error) - set({ featuresLoaded: true }) - } - }, - - reset: () => set(initialState), - - hasFeature: (id) => get().features.includes(id), - - getFeatureInfo: (id) => get().availableFeatures.find((f) => f.id === id), - - getExampleInfo: (id) => get().availableExamples.find((e) => e.id === id), - - getDefinition: () => ({ - name: get().projectName, - framework: get().framework, - features: get().features, - featureOptions: get().featureOptions, - selectedExample: get().selectedExample ?? undefined, - }), - - isFeatureLockedByExample: (id) => { - const { selectedExample, availableExamples } = get() - if (!selectedExample) return false - const example = availableExamples.find((e) => e.id === selectedExample) - return example?.requires.includes(id) ?? false - }, - })), + }, + + loadFeatures: async (): Promise => { + try { + if (import.meta.env.SSR) { + throw new Error( + 'Application Starter features are only loaded in the browser', + ) + } + + const { framework } = get() + const { getFeaturesHandler } = + await import('~/application-starter/api/features') + const data = await getFeaturesHandler(framework) + set({ + availableFeatures: data.features, + availableExamples: data.examples || [], + featuresLoaded: true, + }) + // Apply blank template after features load to set default features + actions.setTemplate('blank') + } catch (error) { + console.error('Failed to load features:', error) + set({ featuresLoaded: true }) + } + }, + + reset: () => set(initialState), + + hasFeature: (id: FeatureId) => get().features.includes(id), + + getFeatureInfo: (id: FeatureId) => + get().availableFeatures.find((f) => f.id === id), + + getExampleInfo: (id: FeatureId) => + get().availableExamples.find((e) => e.id === id), + + getDefinition: (): ProjectDefinition => ({ + name: get().projectName, + framework: get().framework, + features: get().features, + featureOptions: get().featureOptions, + selectedExample: get().selectedExample ?? undefined, + }), + + isFeatureLockedByExample: (id: FeatureId) => { + const { selectedExample, availableExamples } = get() + if (!selectedExample) return false + const example = availableExamples.find((e) => e.id === selectedExample) + return example?.requires.includes(id) ?? false + }, + } + + return actions + }, ) // Selector hooks for common patterns export const useProjectName = () => - useApplicationStarterStore((s) => s.projectName) -export const useFramework = () => useApplicationStarterStore((s) => s.framework) -export const useTailwind = () => useApplicationStarterStore((s) => s.tailwind) -export const useFeatures = () => useApplicationStarterStore((s) => s.features) + useSelector(applicationStarterStore, (s) => s.projectName) +export const useFramework = () => + useSelector(applicationStarterStore, (s) => s.framework) +export const useTailwind = () => + useSelector(applicationStarterStore, (s) => s.tailwind) +export const useFeatures = () => + useSelector(applicationStarterStore, (s) => s.features) export const useFeatureOptions = () => - useApplicationStarterStore((s) => s.featureOptions) + useSelector(applicationStarterStore, (s) => s.featureOptions) export const useSelectedExample = () => - useApplicationStarterStore((s) => s.selectedExample) + useSelector(applicationStarterStore, (s) => s.selectedExample) export const usePackageManager = () => - useApplicationStarterStore((s) => s.packageManager) + useSelector(applicationStarterStore, (s) => s.packageManager) export const useSkipInstall = () => - useApplicationStarterStore((s) => s.skipInstall) -export const useSkipGit = () => useApplicationStarterStore((s) => s.skipGit) + useSelector(applicationStarterStore, (s) => s.skipInstall) +export const useSkipGit = () => + useSelector(applicationStarterStore, (s) => s.skipGit) export const useAvailableFeatures = () => - useApplicationStarterStore((s) => s.availableFeatures) + useSelector(applicationStarterStore, (s) => s.availableFeatures) export const useAvailableExamples = () => - useApplicationStarterStore((s) => s.availableExamples) + useSelector(applicationStarterStore, (s) => s.availableExamples) export const useFeaturesLoaded = () => - useApplicationStarterStore((s) => s.featuresLoaded) + useSelector(applicationStarterStore, (s) => s.featuresLoaded) export const useCustomIntegrations = () => - useApplicationStarterStore((s) => s.customIntegrations) + useSelector(applicationStarterStore, (s) => s.customIntegrations) export const useCustomTemplate = () => - useApplicationStarterStore((s) => s.customTemplate) + useSelector(applicationStarterStore, (s) => s.customTemplate) export const useIntegrationSearch = () => - useApplicationStarterStore((s) => s.integrationSearch) + useSelector(applicationStarterStore, (s) => s.integrationSearch) export const useSelectExample = () => - useApplicationStarterStore((s) => s.selectExample) + applicationStarterStore.actions.selectExample export const useSelectedTemplate = () => - useApplicationStarterStore((s) => s.selectedTemplate) + useSelector(applicationStarterStore, (s) => s.selectedTemplate) // Feature state with exclusive/requirement analysis export function useFeatureState(id: FeatureId) { - const features = useApplicationStarterStore((s) => s.features) - const tailwind = useApplicationStarterStore((s) => s.tailwind) - const availableFeatures = useApplicationStarterStore( + const features = useSelector(applicationStarterStore, (s) => s.features) + const tailwind = useSelector(applicationStarterStore, (s) => s.tailwind) + const availableFeatures = useSelector( + applicationStarterStore, (s) => s.availableFeatures, ) - const isFeatureLockedByExample = useApplicationStarterStore( - (s) => s.isFeatureLockedByExample, - ) const feature = availableFeatures.find((f) => f.id === id) if (!feature) { @@ -477,7 +468,8 @@ export function useFeatureState(id: FeatureId) { } const selected = features.includes(id) - const lockedByExample = isFeatureLockedByExample(id) + const lockedByExample = + applicationStarterStore.actions.isFeatureLockedByExample(id) // Check if disabled due to Tailwind requirement const needsTailwind = feature.requiresTailwind && !tailwind diff --git a/src/components/application-starter/useApplicationStarterUrl.ts b/src/components/application-starter/useApplicationStarterUrl.ts index 6739e9b70..dd0260d3b 100644 --- a/src/components/application-starter/useApplicationStarterUrl.ts +++ b/src/components/application-starter/useApplicationStarterUrl.ts @@ -4,10 +4,11 @@ * Bidirectional sync between URL search params and applicationStarter store. */ +import { useSelector } from '@tanstack/react-store' import { useEffect, useRef } from 'react' import { useNavigate, useSearch } from '@tanstack/react-router' import { useDebouncedCallback } from '@tanstack/react-pacer' -import { useApplicationStarterStore } from './store' +import { applicationStarterStore } from './store' import type { FeatureId } from '~/application-starter/api' import type { FrameworkId } from '~/application-starter/frameworks' // Used in syncToUrl type @@ -27,22 +28,32 @@ export function useApplicationStarterUrl() { const search = useSearch({ strict: false }) as ApplicationStarterSearchParams const isSyncingFromUrl = useRef(false) - const projectName = useApplicationStarterStore((s) => s.projectName) - const framework = useApplicationStarterStore((s) => s.framework) - const features = useApplicationStarterStore((s) => s.features) - const featureOptions = useApplicationStarterStore((s) => s.featureOptions) - const selectedTemplate = useApplicationStarterStore((s) => s.selectedTemplate) - const packageManager = useApplicationStarterStore((s) => s.packageManager) - const tailwind = useApplicationStarterStore((s) => s.tailwind) - const featuresLoaded = useApplicationStarterStore((s) => s.featuresLoaded) - const setProjectName = useApplicationStarterStore((s) => s.setProjectName) - const setFeatures = useApplicationStarterStore((s) => s.setFeatures) - const setFeatureOption = useApplicationStarterStore((s) => s.setFeatureOption) - const setTemplate = useApplicationStarterStore((s) => s.setTemplate) - const setPackageManager = useApplicationStarterStore( - (s) => s.setPackageManager, + const projectName = useSelector(applicationStarterStore, (s) => s.projectName) + const framework = useSelector(applicationStarterStore, (s) => s.framework) + const features = useSelector(applicationStarterStore, (s) => s.features) + const featureOptions = useSelector( + applicationStarterStore, + (s) => s.featureOptions, ) - const setTailwind = useApplicationStarterStore((s) => s.setTailwind) + const selectedTemplate = useSelector( + applicationStarterStore, + (s) => s.selectedTemplate, + ) + const packageManager = useSelector( + applicationStarterStore, + (s) => s.packageManager, + ) + const tailwind = useSelector(applicationStarterStore, (s) => s.tailwind) + const featuresLoaded = useSelector( + applicationStarterStore, + (s) => s.featuresLoaded, + ) + const setProjectName = applicationStarterStore.actions.setProjectName + const setFeatures = applicationStarterStore.actions.setFeatures + const setFeatureOption = applicationStarterStore.actions.setFeatureOption + const setTemplate = applicationStarterStore.actions.setTemplate + const setPackageManager = applicationStarterStore.actions.setPackageManager + const setTailwind = applicationStarterStore.actions.setTailwind // Initialize from URL on mount (only once when features load) const initializedRef = useRef(false) @@ -80,7 +91,7 @@ export function useApplicationStarterUrl() { setFeatures( Array.from( new Set([ - ...useApplicationStarterStore.getState().features, + ...applicationStarterStore.state.features, ...featureList, ]), ), @@ -220,18 +231,28 @@ export function useApplicationStarterUrl() { * Generate CLI command from current state */ export function useCliCommand(): string { - const projectName = useApplicationStarterStore((s) => s.projectName) - const framework = useApplicationStarterStore((s) => s.framework) - const features = useApplicationStarterStore((s) => s.features) - const featureOptions = useApplicationStarterStore((s) => s.featureOptions) - const selectedExample = useApplicationStarterStore((s) => s.selectedExample) - const availableExamples = useApplicationStarterStore( + const projectName = useSelector(applicationStarterStore, (s) => s.projectName) + const framework = useSelector(applicationStarterStore, (s) => s.framework) + const features = useSelector(applicationStarterStore, (s) => s.features) + const featureOptions = useSelector( + applicationStarterStore, + (s) => s.featureOptions, + ) + const selectedExample = useSelector( + applicationStarterStore, + (s) => s.selectedExample, + ) + const availableExamples = useSelector( + applicationStarterStore, (s) => s.availableExamples, ) - const tailwind = useApplicationStarterStore((s) => s.tailwind) - const packageManager = useApplicationStarterStore((s) => s.packageManager) - const skipInstall = useApplicationStarterStore((s) => s.skipInstall) - const skipGit = useApplicationStarterStore((s) => s.skipGit) + const tailwind = useSelector(applicationStarterStore, (s) => s.tailwind) + const packageManager = useSelector( + applicationStarterStore, + (s) => s.packageManager, + ) + const skipInstall = useSelector(applicationStarterStore, (s) => s.skipInstall) + const skipGit = useSelector(applicationStarterStore, (s) => s.skipGit) let cmd = `npx @tanstack/cli@latest create ${projectName}` cmd += ' --agent' diff --git a/src/components/game/engine/GameEngine.ts b/src/components/game/engine/GameEngine.ts index e98a06074..16f3f8ffa 100644 --- a/src/components/game/engine/GameEngine.ts +++ b/src/components/game/engine/GameEngine.ts @@ -1,5 +1,6 @@ import * as THREE from 'three' -import { useGameStore } from '../hooks/useGameStore' +import type { Subscription } from '@tanstack/react-store' +import { gameStore } from '../hooks/useGameStore' import { preloadModels } from './loaders/ModelLoader' import { preloadGameFonts } from './loaders/FontLoader' import { Sky } from './entities/Sky' @@ -64,7 +65,7 @@ export class GameEngine { private camera: THREE.PerspectiveCamera private clock: THREE.Clock private animationFrameId: number | null = null - private unsubscribers: Array<() => void> = [] + private unsubscribers: Array = [] private isDisposed = false private isPaused = false private raycaster = new THREE.Raycaster() @@ -206,7 +207,7 @@ export class GameEngine { this.scene.add(this.aiDebug.group) // Initialize boat model - const { boatType } = useGameStore.getState() + const { boatType } = gameStore.state this.boat.setBoatType(boatType) // Setup subscriptions @@ -334,34 +335,34 @@ export class GameEngine { } private initializeGameData(): void { - const state = useGameStore.getState() + const state = gameStore.state if (state.islands.length === 0) { // Generate islands const generatedIslands = generateIslands(publicLibraries) - state.setIslands(generatedIslands) + gameStore.actions.setIslands(generatedIslands) // Generate rock colliders const rockColliders = generateRockColliders(generatedIslands, 30, 140) - state.setRockColliders(rockColliders) + gameStore.actions.setRockColliders(rockColliders) // Generate coins const generatedCoins = generateCoins(generatedIslands) - state.setCoins(generatedCoins) + gameStore.actions.setCoins(generatedCoins) } // Initialize entities with data - const islands = useGameStore.getState().islands + const islands = gameStore.state.islands this.islands.setIslands(islands, []) this.oceanRocks.generate(islands, 30, 140) - this.coins.setCoins(useGameStore.getState().coins) + this.coins.setCoins(gameStore.state.coins) // Set ocean island gradients this.updateOceanIslandPositions(islands, [], []) } private setupSubscriptions(): void { - const initialState = useGameStore.getState() + const initialState = gameStore.state // Handle loading directly into battle stage (page reload while in battle) console.log('[Game Init] State:', { @@ -375,9 +376,9 @@ export class GameEngine { // Generate expanded islands if needed if (initialState.expandedIslands.length === 0) { const partnerIslands = generateExpandedIslands(ACTIVE_PARTNERS) - initialState.setExpandedIslands(partnerIslands) + gameStore.actions.setExpandedIslands(partnerIslands) } - const expandedIslands = useGameStore.getState().expandedIslands + const expandedIslands = gameStore.state.expandedIslands // Generate showcase islands if showcase was unlocked const showcaseIslands = initialState.showcaseIslands @@ -385,7 +386,7 @@ export class GameEngine { let cornerIslands = initialState.cornerIslands if (initialState.cornersUnlocked && cornerIslands.length === 0) { cornerIslands = generateCornerIslands() - initialState.setCornerIslands(cornerIslands) + gameStore.actions.setCornerIslands(cornerIslands) } if (initialState.showcaseUnlocked && showcaseIslands.length === 0) { @@ -404,7 +405,7 @@ export class GameEngine { '[Game Init] Generated showcase islands:', generated.length, ) - initialState.setShowcaseIslands(generated) + gameStore.actions.setShowcaseIslands(generated) this.islands.setIslands( initialState.islands, expandedIslands, @@ -455,7 +456,7 @@ export class GameEngine { initialState.coins, allIslands, ) - initialState.setCoins(expandedCoins) + gameStore.actions.setCoins(expandedCoins) } // Set boat type @@ -486,7 +487,7 @@ export class GameEngine { let prevCornersUnlocked = initialState.cornersUnlocked this.unsubscribers.push( - useGameStore.subscribe((state) => { + gameStore.subscribe((state) => { // Phase change (detect reset - going back to intro) if (state.phase !== prevPhase) { const wasReset = prevPhase !== 'intro' && state.phase === 'intro' @@ -521,9 +522,9 @@ export class GameEngine { if (state.stage === 'battle') { if (state.expandedIslands.length === 0) { const partnerIslands = generateExpandedIslands(ACTIVE_PARTNERS) - state.setExpandedIslands(partnerIslands) + gameStore.actions.setExpandedIslands(partnerIslands) } - const expandedIslands = useGameStore.getState().expandedIslands + const expandedIslands = gameStore.state.expandedIslands this.islands.setIslands( state.islands, expandedIslands, @@ -546,7 +547,7 @@ export class GameEngine { ...state.showcaseIslands, ] const expandedCoins = generateExpandedCoins(state.coins, allIslands) - state.setCoins(expandedCoins) + gameStore.actions.setCoins(expandedCoins) this.aiSystem.spawn(6) } @@ -568,7 +569,7 @@ export class GameEngine { ) // Expand world boundary for showcase zone - state.setWorldBoundary(520) + gameStore.actions.setWorldBoundary(520) // Spawn tough outer rim AIs for the showcase zone this.aiSystem.spawn(8, true) @@ -585,8 +586,8 @@ export class GameEngine { generated.length, ) // Get fresh state for current islands - const currentState = useGameStore.getState() - currentState.setShowcaseIslands(generated) + const currentState = gameStore.state + gameStore.actions.setShowcaseIslands(generated) // Update islands entity with showcase islands this.islands.setIslands( @@ -627,7 +628,7 @@ export class GameEngine { // Generate corner islands const cornerIslands = generateCornerIslands() - state.setCornerIslands(cornerIslands) + gameStore.actions.setCornerIslands(cornerIslands) // Spawn corner boss AIs this.aiSystem.spawnCornerBosses() @@ -674,7 +675,7 @@ export class GameEngine { // Delay spawn slightly to let state settle setTimeout(() => { // Get fresh state to check unlock status - const currentState = useGameStore.getState() + const currentState = gameStore.state this.aiSystem.spawn(6) // Spawn outer rim AIs if showcase is unlocked if (currentState.showcaseUnlocked) { @@ -733,7 +734,7 @@ export class GameEngine { } private update(delta: number, time: number): void { - const state = useGameStore.getState() + const state = gameStore.state // Always update sky and ocean animation this.sky.update(time) @@ -748,7 +749,7 @@ export class GameEngine { this.cameraSystem.update(delta, time) // Respawn coins that have been collected for long enough - useGameStore.getState().respawnCoins() + gameStore.actions.respawnCoins() if (state.stage === 'battle') { this.aiSystem.update(delta) @@ -756,8 +757,8 @@ export class GameEngine { this.aiDebug.update() // Health regeneration - const { boatHealth, shipStats, purchasedBoosts, setBoatHealth } = - useGameStore.getState() + const { boatHealth, shipStats, purchasedBoosts } = gameStore.state + const { setBoatHealth } = gameStore.actions const totalMaxHealth = shipStats.maxHealth + purchasedBoosts.permHealth * 25 if (boatHealth < totalMaxHealth && shipStats.healthRegen > 0) { @@ -937,7 +938,7 @@ export class GameEngine { // Re-initialize with current game data const { islands, expandedIslands, showcaseIslands, cornerIslands } = - useGameStore.getState() + gameStore.state this.islands.setIslands( islands, expandedIslands, @@ -952,7 +953,7 @@ export class GameEngine { this.stop() // Cleanup subscriptions - this.unsubscribers.forEach((unsub) => unsub()) + this.unsubscribers.forEach((sub) => sub.unsubscribe()) this.unsubscribers = [] // Cleanup systems diff --git a/src/components/game/engine/entities/AIDebug.ts b/src/components/game/engine/entities/AIDebug.ts index 7dd4b23ac..a079dd477 100644 --- a/src/components/game/engine/entities/AIDebug.ts +++ b/src/components/game/engine/entities/AIDebug.ts @@ -1,5 +1,5 @@ import * as THREE from 'three' -import { useGameStore } from '../../hooks/useGameStore' +import { gameStore } from '../../hooks/useGameStore' import type { AISystem } from '../systems/AISystem' export class AIDebug { @@ -18,7 +18,7 @@ export class AIDebug { } update(): void { - const { showCollisionDebug, stage } = useGameStore.getState() + const { showCollisionDebug, stage } = gameStore.state // Only show in debug mode and battle stage this.group.visible = showCollisionDebug && stage === 'battle' diff --git a/src/components/game/engine/entities/AIShips.ts b/src/components/game/engine/entities/AIShips.ts index bd8297e2f..80c128e4a 100644 --- a/src/components/game/engine/entities/AIShips.ts +++ b/src/components/game/engine/entities/AIShips.ts @@ -1,7 +1,7 @@ import * as THREE from 'three' import { modelLoader } from '../loaders/ModelLoader' import { getWaveHeight } from './Ocean' -import { useGameStore, type OtherPlayer } from '../../hooks/useGameStore' +import { gameStore, type OtherPlayer } from '../../hooks/useGameStore' interface AIShipData { id: string @@ -29,7 +29,7 @@ export class AIShips { } spawn(_count: number): void { - const _otherPlayers = useGameStore.getState().otherPlayers + const _otherPlayers = gameStore.state.otherPlayers // Ships will be created in updatePlayers when AI system adds them } @@ -99,7 +99,7 @@ export class AIShips { } update(time: number): void { - const { boatPosition, otherPlayers, stage } = useGameStore.getState() + const { boatPosition, otherPlayers, stage } = gameStore.state if (stage !== 'battle') { this.group.visible = false diff --git a/src/components/game/engine/entities/BoundaryWalls.ts b/src/components/game/engine/entities/BoundaryWalls.ts index abd3207fb..c5af29e09 100644 --- a/src/components/game/engine/entities/BoundaryWalls.ts +++ b/src/components/game/engine/entities/BoundaryWalls.ts @@ -1,5 +1,5 @@ import * as THREE from 'three' -import { useGameStore } from '../../hooks/useGameStore' +import { gameStore } from '../../hooks/useGameStore' const PLANE_SIZE = 100 const PLANE_OPACITY = 0.6 @@ -42,7 +42,7 @@ export class BoundaryWalls { } update(delta: number): void { - const { boundaryEdges, worldBoundary, phase } = useGameStore.getState() + const { boundaryEdges, worldBoundary, phase } = gameStore.state for (const plane of this.planes) { // Hide when not playing diff --git a/src/components/game/engine/entities/Islands.ts b/src/components/game/engine/entities/Islands.ts index b5ad73ea0..8d9cf1f3b 100644 --- a/src/components/game/engine/entities/Islands.ts +++ b/src/components/game/engine/entities/Islands.ts @@ -2,7 +2,7 @@ import * as THREE from 'three' import type { IslandData } from '../../utils/islandGenerator' import { COLORS, getLibraryColor } from '../../utils/colors' import { modelLoader } from '../loaders/ModelLoader' -import { useGameStore } from '../../hooks/useGameStore' +import { gameStore } from '../../hooks/useGameStore' // @ts-expect-error - troika-three-text has no types import { Text } from 'troika-three-text' @@ -1257,7 +1257,7 @@ export class Islands { discoveryProgress, discoveredIslands, showCollisionDebug, - } = useGameStore.getState() + } = gameStore.state for (const [id, instance] of this.instances) { // Distance culling diff --git a/src/components/game/engine/systems/AISystem.ts b/src/components/game/engine/systems/AISystem.ts index 95bb05e31..30e8f8d90 100644 --- a/src/components/game/engine/systems/AISystem.ts +++ b/src/components/game/engine/systems/AISystem.ts @@ -1,5 +1,5 @@ import { - useGameStore, + gameStore, type OtherPlayer, type Cannonball, type AIDifficulty, @@ -350,11 +350,11 @@ export class AISystem { if (outerRim) { // Add to existing AIs - const { otherPlayers } = useGameStore.getState() - useGameStore.getState().setOtherPlayers([...otherPlayers, ...opponents]) + const { otherPlayers } = gameStore.state + gameStore.actions.setOtherPlayers([...otherPlayers, ...opponents]) states.forEach((state, id) => this.aiStates.set(id, state)) } else { - useGameStore.getState().setOtherPlayers(opponents) + gameStore.actions.setOtherPlayers(opponents) this.aiStates = states this.initialized = true } @@ -367,8 +367,8 @@ export class AISystem { const { opponents, states } = generateCornerBosses(this.spawnCount) - const { otherPlayers } = useGameStore.getState() - useGameStore.getState().setOtherPlayers([...otherPlayers, ...opponents]) + const { otherPlayers } = gameStore.state + gameStore.actions.setOtherPlayers([...otherPlayers, ...opponents]) states.forEach((state, id) => this.aiStates.set(id, state)) this.spawnCount += opponents.length @@ -381,7 +381,7 @@ export class AISystem { id: string leashRadius: number }> { - const { otherPlayers } = useGameStore.getState() + const { otherPlayers } = gameStore.state const territories: Array<{ homePosition: [number, number] color: string @@ -406,7 +406,7 @@ export class AISystem { } update(delta: number): void { - const state = useGameStore.getState() + const state = gameStore.state const { otherPlayers, boatPosition, @@ -662,12 +662,16 @@ export class AISystem { }) if (newCannonballs.length > 0) { - useGameStore.setState({ + gameStore.setState((state) => ({ + ...state, otherPlayers: updatedPlayers, cannonballs: [...cannonballs, ...newCannonballs], - }) + })) } else { - useGameStore.setState({ otherPlayers: updatedPlayers }) + gameStore.setState((state) => ({ + ...state, + otherPlayers: updatedPlayers, + })) } } diff --git a/src/components/game/engine/systems/BoatControlSystem.ts b/src/components/game/engine/systems/BoatControlSystem.ts index f32c79a95..7f4f35f7f 100644 --- a/src/components/game/engine/systems/BoatControlSystem.ts +++ b/src/components/game/engine/systems/BoatControlSystem.ts @@ -1,4 +1,4 @@ -import { useGameStore } from '../../hooks/useGameStore' +import { gameStore } from '../../hooks/useGameStore' import { findNearestIsland } from '../../utils/islandGenerator' import { checkIslandCollision, checkRockCollision } from '../../utils/collision' import { getPointerState } from '../../ui/TouchControls' @@ -63,14 +63,14 @@ export class BoatControlSystem { } private handleKeyDown(e: KeyboardEvent): void { + const { shipStats } = gameStore.state const { setMovingForward, setMovingBackward, setTurningLeft, setTurningRight, fireCannon, - shipStats, - } = useGameStore.getState() + } = gameStore.actions if (e.code === 'ArrowUp' || e.code === 'KeyW') { e.preventDefault() @@ -90,7 +90,7 @@ export class BoatControlSystem { } if (e.code === 'Space' && !e.repeat) { e.preventDefault() - const { purchasedBoosts } = useGameStore.getState() + const { purchasedBoosts } = gameStore.state // Track space held for gatling or rapid fire (auto-loader) if (shipStats.gatlingGuns || purchasedBoosts.rapidFire) { this.spaceHeld = true @@ -105,7 +105,7 @@ export class BoatControlSystem { setMovingBackward, setTurningLeft, setTurningRight, - } = useGameStore.getState() + } = gameStore.actions if (e.code === 'ArrowUp' || e.code === 'KeyW') { setMovingForward(false) @@ -125,7 +125,7 @@ export class BoatControlSystem { } update(delta: number): void { - const state = useGameStore.getState() + const state = gameStore.state const { boatPosition, boatRotation, @@ -143,11 +143,9 @@ export class BoatControlSystem { shipStats, speedBoostEndTime, purchasedBoosts, - setBoatPosition, - setBoatRotation, - setBoatVelocity, - fireGatling, } = state + const { setBoatPosition, setBoatRotation, setBoatVelocity, fireGatling } = + gameStore.actions // Combine islands for collision in battle stage (includes partner, showcase, and corner islands) const allIslands = @@ -162,7 +160,7 @@ export class BoatControlSystem { // Fire side cannons while space is held (auto-loader) if (this.spaceHeld && purchasedBoosts.rapidFire) { - const { fireCannon } = useGameStore.getState() + const { fireCannon } = gameStore.actions fireCannon() } @@ -271,7 +269,7 @@ export class BoatControlSystem { } // Ship-to-ship collision (with AI ships) - const { otherPlayers } = useGameStore.getState() + const { otherPlayers } = gameStore.state const AI_SHIP_RADIUS = 1.2 for (const ship of otherPlayers) { const dx = newX - ship.position[0] @@ -312,8 +310,8 @@ export class BoatControlSystem { } // Boundary handling - const { worldBoundary, boundaryEdges, setBoundaryEdges } = - useGameStore.getState() + const { worldBoundary, boundaryEdges } = gameStore.state + const { setBoundaryEdges } = gameStore.actions const BOUNDARY_THRESHOLD = 2 const atWest = newX <= -worldBoundary + BOUNDARY_THRESHOLD @@ -352,12 +350,8 @@ export class BoatControlSystem { // Update nearby island detection (uses allIslands which includes partner islands in battle stage) const nearby = findNearestIsland(newPosition, allIslands, 10) - const { - nearbyIsland, - discoveryProgress, - setNearbyIsland, - setDiscoveryProgress, - } = useGameStore.getState() + const { nearbyIsland, discoveryProgress } = gameStore.state + const { setNearbyIsland, setDiscoveryProgress } = gameStore.actions if (nearby?.id !== nearbyIsland?.id) { setNearbyIsland(nearby) diff --git a/src/components/game/engine/systems/CameraSystem.ts b/src/components/game/engine/systems/CameraSystem.ts index adf9c8995..84507b18a 100644 --- a/src/components/game/engine/systems/CameraSystem.ts +++ b/src/components/game/engine/systems/CameraSystem.ts @@ -1,5 +1,5 @@ import * as THREE from 'three' -import { useGameStore } from '../../hooks/useGameStore' +import { gameStore } from '../../hooks/useGameStore' const BASE_FOV = 20 const _DEBUG_ZOOM_HEIGHT = 400 @@ -26,7 +26,7 @@ export class CameraSystem { } update(_delta: number, _time: number): void { - const { boatPosition, shipStats, debugZoomOut } = useGameStore.getState() + const { boatPosition, shipStats, debugZoomOut } = gameStore.state // Debug zoom out mode - bird's eye view of entire map if (debugZoomOut) { diff --git a/src/components/game/engine/systems/CannonballSystem.ts b/src/components/game/engine/systems/CannonballSystem.ts index 63d508b92..847ffa7d3 100644 --- a/src/components/game/engine/systems/CannonballSystem.ts +++ b/src/components/game/engine/systems/CannonballSystem.ts @@ -1,4 +1,4 @@ -import { useGameStore } from '../../hooks/useGameStore' +import { gameStore } from '../../hooks/useGameStore' import type { Cannonballs } from '../entities/Cannonballs' const GRAVITY = -15 @@ -7,16 +7,9 @@ const HIT_RADIUS = 1.5 export class CannonballSystem { update(delta: number, cannonballsEntity: Cannonballs): void { - const state = useGameStore.getState() - const { - cannonballs, - updateCannonballs, - otherPlayers, - setOtherPlayers, - boatPosition, - boatHealth, - setPhase, - } = state + const state = gameStore.state + const { cannonballs, otherPlayers, boatPosition, boatHealth } = state + const { updateCannonballs, setOtherPlayers, setPhase } = gameStore.actions const now = Date.now() const dt = Math.min(delta, 0.1) @@ -82,7 +75,7 @@ export class CannonballSystem { const playerHit = hitsToProcess.find((h) => h.playerId === 'player') if (playerHit) { const newHealth = Math.max(0, boatHealth - 20) - useGameStore.setState({ boatHealth: newHealth }) + gameStore.setState((state) => ({ ...state, boatHealth: newHealth })) if (newHealth <= 0) { setPhase('gameover') @@ -101,7 +94,7 @@ export class CannonballSystem { // Count kills (ships that dropped to 0 health) const killedCount = updatedPlayers.filter((p) => p.health <= 0).length if (killedCount > 0) { - const { addKill } = useGameStore.getState() + const { addKill } = gameStore.actions for (let i = 0; i < killedCount; i++) { addKill() } diff --git a/src/components/game/engine/systems/CoinSystem.ts b/src/components/game/engine/systems/CoinSystem.ts index 1470815ac..dd536fa97 100644 --- a/src/components/game/engine/systems/CoinSystem.ts +++ b/src/components/game/engine/systems/CoinSystem.ts @@ -1,11 +1,12 @@ -import { useGameStore } from '../../hooks/useGameStore' +import { gameStore } from '../../hooks/useGameStore' import type { Coins } from '../entities/Coins' const COIN_COLLECT_RADIUS = 1.5 export class CoinSystem { update(_delta: number, _coinsEntity: Coins): void { - const { boatPosition, coins, collectCoin } = useGameStore.getState() + const { boatPosition, coins } = gameStore.state + const { collectCoin } = gameStore.actions for (const coin of coins) { if (coin.collected) continue diff --git a/src/components/game/engine/systems/DiscoverySystem.ts b/src/components/game/engine/systems/DiscoverySystem.ts index f2fa9b448..6a2a45099 100644 --- a/src/components/game/engine/systems/DiscoverySystem.ts +++ b/src/components/game/engine/systems/DiscoverySystem.ts @@ -1,19 +1,14 @@ -import { useGameStore } from '../../hooks/useGameStore' +import { gameStore } from '../../hooks/useGameStore' const DISCOVERY_RADIUS = 8 const DISCOVERY_TIME = 3 // Seconds to fully discover export class DiscoverySystem { update(delta: number): void { - const state = useGameStore.getState() - const { - boatPosition, - nearbyIsland, - discoveryProgress, - discoveredIslands, - setDiscoveryProgress, - discoverIsland, - } = state + const state = gameStore.state + const { boatPosition, nearbyIsland, discoveryProgress, discoveredIslands } = + state + const { setDiscoveryProgress, discoverIsland } = gameStore.actions if (!nearbyIsland || discoveredIslands.has(nearbyIsland.id)) return diff --git a/src/components/game/hooks/useGameStore.ts b/src/components/game/hooks/useGameStore.ts index 4f68e4d55..a9ba908cc 100644 --- a/src/components/game/hooks/useGameStore.ts +++ b/src/components/game/hooks/useGameStore.ts @@ -1,5 +1,5 @@ import { useEffect } from 'react' -import { create } from 'zustand' +import { createStore } from '@tanstack/react-store' import type { IslandData } from '../utils/islandGenerator' import { type Upgrade, @@ -101,25 +101,20 @@ function extractPersistedState(state: { } } -interface GameState { +type GameState = { // Game phase phase: 'intro' | 'playing' | 'upgrading' | 'complete' | 'gameover' - setPhase: (phase: GameState['phase']) => void // Game stage (exploration = dinghy, battle = ship + multiplayer) stage: GameStage - setStage: (stage: GameStage) => void // Boat type and upgrades boatType: BoatType - setBoatType: (type: BoatType) => void // Ship stats (upgradeable) shipStats: ShipStats unlockedUpgrades: Upgrade[] lastUnlockedUpgrade: Upgrade | null // For showing notification - applyShipUpgrade: (upgrade: Upgrade) => void - clearLastUnlockedUpgrade: () => void // Boat state boatPosition: [number, number, number] @@ -131,32 +126,16 @@ interface GameState { isTurningLeft: boolean isTurningRight: boolean - // Boat actions - setBoatPosition: (pos: [number, number, number]) => void - setBoatRotation: (rot: number) => void - setBoatVelocity: (vel: number) => void - setBoatHealth: (health: number) => void - setMovingForward: (moving: boolean) => void - setMovingBackward: (moving: boolean) => void - setTurningLeft: (turning: boolean) => void - setTurningRight: (turning: boolean) => void - // World boundary (expands after upgrade) worldBoundary: number - setWorldBoundary: (boundary: number) => void // Other players (AI + real multiplayer) otherPlayers: OtherPlayer[] - setOtherPlayers: (players: OtherPlayer[]) => void - updateOtherPlayer: (id: string, data: Partial) => void // Discovery discoveredIslands: Set nearbyIsland: IslandData | null discoveryProgress: number // 0-1 progress toward discovering current nearby island - discoverIsland: (id: string) => void - setNearbyIsland: (island: IslandData | null) => void - setDiscoveryProgress: (progress: number) => void // Islands (core library islands + expanded partner/showcase islands) islands: IslandData[] @@ -166,23 +145,13 @@ interface GameState { showcaseUnlocked: boolean // Whether showcase expansion is unlocked cornersUnlocked: boolean // Whether corner boss islands are unlocked gameWon: boolean // Whether the player has captured all 4 corners - setIslands: (islands: IslandData[]) => void - setExpandedIslands: (islands: IslandData[]) => void - setShowcaseIslands: (islands: IslandData[]) => void - setCornerIslands: (islands: IslandData[]) => void - unlockShowcase: () => void - unlockCorners: () => void // Rock colliders rockColliders: RockCollider[] - setRockColliders: (rocks: RockCollider[]) => void // Coins coins: CoinData[] coinsCollected: number - setCoins: (coins: CoinData[]) => void - collectCoin: (id: number) => void - respawnCoins: () => void // Respawn coins that have been collected for long enough // Boundary collision (which edges are being hit) boundaryEdges: { @@ -191,63 +160,87 @@ interface GameState { east: boolean west: boolean } - setBoundaryEdges: (edges: { - north: boolean - south: boolean - east: boolean - west: boolean - }) => void // Cannonballs cannonballs: Cannonball[] lastFireTime: number lastGatlingTime: number - fireCannon: () => void - fireGatling: () => void - updateCannonballs: (cannonballs: Cannonball[]) => void - removeCannonball: (id: number) => void // Audio isMuted: boolean - toggleMute: () => void // Shop isShopOpen: boolean - openShop: () => void - closeShop: () => void - purchaseItem: (itemType: ShopItemType) => boolean // Active items/effects compassTarget: IslandData | null // Island the compass is pointing to speedBoostEndTime: number | null // Timestamp when speed boost ends - setCompassTarget: (island: IslandData | null) => void - clearCompassOnDiscover: (islandId: string) => void // Debug showCollisionDebug: boolean - setShowCollisionDebug: (show: boolean) => void debugZoomOut: boolean - setDebugZoomOut: (zoom: boolean) => void // Stats tracking kills: number deaths: number - addKill: () => void - addDeath: () => void // Purchased permanent boosts purchasedBoosts: PurchasedBoosts +} - // Upgrade to ship (called when all core islands discovered) +type GameActions = { + setPhase: (phase: GameState['phase']) => void + setStage: (stage: GameStage) => void + setBoatType: (type: BoatType) => void + applyShipUpgrade: (upgrade: Upgrade) => void + clearLastUnlockedUpgrade: () => void + setBoatPosition: (pos: [number, number, number]) => void + setBoatRotation: (rot: number) => void + setBoatVelocity: (vel: number) => void + setBoatHealth: (health: number) => void + setMovingForward: (moving: boolean) => void + setMovingBackward: (moving: boolean) => void + setTurningLeft: (turning: boolean) => void + setTurningRight: (turning: boolean) => void + setWorldBoundary: (boundary: number) => void + setOtherPlayers: (players: OtherPlayer[]) => void + updateOtherPlayer: (id: string, data: Partial) => void + discoverIsland: (id: string) => void + setNearbyIsland: (island: IslandData | null) => void + setDiscoveryProgress: (progress: number) => void + setIslands: (islands: IslandData[]) => void + setExpandedIslands: (islands: IslandData[]) => void + setShowcaseIslands: (islands: IslandData[]) => void + setCornerIslands: (islands: IslandData[]) => void + unlockShowcase: () => void + unlockCorners: () => void + setRockColliders: (rocks: RockCollider[]) => void + setCoins: (coins: CoinData[]) => void + collectCoin: (id: number) => void + respawnCoins: () => void // Respawn coins that have been collected for long enough + setBoundaryEdges: (edges: { + north: boolean + south: boolean + east: boolean + west: boolean + }) => void + fireCannon: () => void + fireGatling: () => void + updateCannonballs: (cannonballs: Cannonball[]) => void + removeCannonball: (id: number) => void + toggleMute: () => void + openShop: () => void + closeShop: () => void + purchaseItem: (itemType: ShopItemType) => boolean + setCompassTarget: (island: IslandData | null) => void + clearCompassOnDiscover: (islandId: string) => void + setShowCollisionDebug: (show: boolean) => void + setDebugZoomOut: (zoom: boolean) => void + addKill: () => void + addDeath: () => void upgradeToShip: () => void - - // Reset reset: () => void - - // Restart battle (keep discoveries, reset battle state) restartBattle: () => void - - // Start over (full reset including localStorage) startOver: () => void } @@ -256,14 +249,14 @@ const INITIAL_WORLD_BOUNDARY = 85 // Expanded world boundary after upgrading to ship const EXPANDED_WORLD_BOUNDARY = 180 -const initialState = { - phase: 'intro' as const, - stage: 'exploration' as GameStage, - boatType: 'dinghy' as BoatType, - shipStats: { ...BASE_SHIP_STATS } as ShipStats, - unlockedUpgrades: [] as Upgrade[], - lastUnlockedUpgrade: null as Upgrade | null, - boatPosition: [0, 0, 0] as [number, number, number], +const initialState: GameState = { + phase: 'intro', + stage: 'exploration', + boatType: 'dinghy', + shipStats: { ...BASE_SHIP_STATS }, + unlockedUpgrades: [], + lastUnlockedUpgrade: null, + boatPosition: [0, 0, 0], boatRotation: 0, boatVelocity: 0, boatHealth: 100, @@ -272,27 +265,27 @@ const initialState = { isTurningLeft: false, isTurningRight: false, worldBoundary: INITIAL_WORLD_BOUNDARY, - otherPlayers: [] as OtherPlayer[], + otherPlayers: [], discoveredIslands: new Set(), nearbyIsland: null, discoveryProgress: 0, - islands: [] as IslandData[], - expandedIslands: [] as IslandData[], - showcaseIslands: [] as IslandData[], - cornerIslands: [] as IslandData[], + islands: [], + expandedIslands: [], + showcaseIslands: [], + cornerIslands: [], showcaseUnlocked: false, cornersUnlocked: false, gameWon: false, - rockColliders: [] as RockCollider[], - coins: [] as CoinData[], + rockColliders: [], + coins: [], coinsCollected: 0, boundaryEdges: { north: false, south: false, east: false, west: false }, - cannonballs: [] as Cannonball[], + cannonballs: [], lastFireTime: 0, lastGatlingTime: 0, isMuted: false, isShopOpen: false, - compassTarget: null as IslandData | null, + compassTarget: null, speedBoostEndTime: null as number | null, showCollisionDebug: false, debugZoomOut: false, @@ -303,7 +296,7 @@ const initialState = { permAccel: 0, permHealth: 0, rapidFire: false, - } as PurchasedBoosts, + }, } // Load initial state from localStorage if available @@ -313,699 +306,738 @@ const loadedState = loadFromLocalStorage() let pendingCompassTargetId: string | null = loadedState?.compassTargetId ?? null let pendingCollectedCoinIds: number[] = loadedState?.collectedCoinIds ?? [] -export const useGameStore = create()((set, get) => ({ - ...initialState, - // Override with loaded state if available - ...(loadedState - ? { - discoveredIslands: new Set(loadedState.discoveredIslands || []), - coinsCollected: - loadedState.coinsCollected ?? initialState.coinsCollected, - unlockedUpgrades: - loadedState.unlockedUpgrades ?? initialState.unlockedUpgrades, - shipStats: loadedState.shipStats ?? initialState.shipStats, - kills: loadedState.kills ?? initialState.kills, - deaths: loadedState.deaths ?? initialState.deaths, - stage: loadedState.stage ?? initialState.stage, - boatType: loadedState.boatType ?? initialState.boatType, - boatPosition: loadedState.boatPosition ?? initialState.boatPosition, - boatRotation: loadedState.boatRotation ?? initialState.boatRotation, - boatHealth: loadedState.boatHealth ?? initialState.boatHealth, - // Restore speed boost if it hasn't expired - speedBoostEndTime: - loadedState.speedBoostEndTime && - loadedState.speedBoostEndTime > Date.now() - ? loadedState.speedBoostEndTime - : null, - phase: - loadedState.discoveredIslands && - loadedState.discoveredIslands.length > 0 - ? ('playing' as const) - : ('intro' as const), - worldBoundary: loadedState.showcaseUnlocked - ? 520 // Showcase zone boundary - : loadedState.stage === 'battle' - ? EXPANDED_WORLD_BOUNDARY - : INITIAL_WORLD_BOUNDARY, - showcaseUnlocked: loadedState.showcaseUnlocked ?? false, - cornersUnlocked: loadedState.cornersUnlocked ?? false, - purchasedBoosts: - loadedState.purchasedBoosts ?? initialState.purchasedBoosts, - } - : {}), - - setPhase: (phase) => set({ phase }), - setStage: (stage) => set({ stage }), - setBoatType: (boatType) => set({ boatType }), - applyShipUpgrade: (upgrade: Upgrade) => { - const { shipStats, unlockedUpgrades, boatHealth } = get() - // Check if we already have this exact upgrade (same type and tier) - const alreadyHave = unlockedUpgrades.some( - (u) => u.type === upgrade.type && u.tier === upgrade.tier, - ) - if (alreadyHave) return - const newStats = applyUpgrade(shipStats, upgrade) - - // If maxHealth increased, also heal by that amount - const healthGain = newStats.maxHealth - shipStats.maxHealth - const newHealth = healthGain > 0 ? boatHealth + healthGain : boatHealth - - set({ - shipStats: newStats, - unlockedUpgrades: [...unlockedUpgrades, upgrade], - boatHealth: newHealth, - }) +export const gameStore = createStore( + { + ...initialState, + // Override with loaded state if available + ...(loadedState + ? { + discoveredIslands: new Set(loadedState.discoveredIslands || []), + coinsCollected: + loadedState.coinsCollected ?? initialState.coinsCollected, + unlockedUpgrades: + loadedState.unlockedUpgrades ?? initialState.unlockedUpgrades, + shipStats: loadedState.shipStats ?? initialState.shipStats, + kills: loadedState.kills ?? initialState.kills, + deaths: loadedState.deaths ?? initialState.deaths, + stage: loadedState.stage ?? initialState.stage, + boatType: loadedState.boatType ?? initialState.boatType, + boatPosition: loadedState.boatPosition ?? initialState.boatPosition, + boatRotation: loadedState.boatRotation ?? initialState.boatRotation, + boatHealth: loadedState.boatHealth ?? initialState.boatHealth, + // Restore speed boost if it hasn't expired + speedBoostEndTime: + loadedState.speedBoostEndTime && + loadedState.speedBoostEndTime > Date.now() + ? loadedState.speedBoostEndTime + : null, + phase: + loadedState.discoveredIslands && + loadedState.discoveredIslands.length > 0 + ? ('playing' as const) + : ('intro' as const), + worldBoundary: loadedState.showcaseUnlocked + ? 520 // Showcase zone boundary + : loadedState.stage === 'battle' + ? EXPANDED_WORLD_BOUNDARY + : INITIAL_WORLD_BOUNDARY, + showcaseUnlocked: loadedState.showcaseUnlocked ?? false, + cornersUnlocked: loadedState.cornersUnlocked ?? false, + purchasedBoosts: + loadedState.purchasedBoosts ?? initialState.purchasedBoosts, + } + : {}), }, - clearLastUnlockedUpgrade: () => set({ lastUnlockedUpgrade: null }), - - setBoatPosition: (boatPosition) => set({ boatPosition }), - setBoatRotation: (boatRotation) => set({ boatRotation }), - setBoatVelocity: (boatVelocity) => set({ boatVelocity }), - setBoatHealth: (boatHealth) => set({ boatHealth }), - setMovingForward: (isMovingForward) => set({ isMovingForward }), - setMovingBackward: (isMovingBackward) => set({ isMovingBackward }), - setTurningLeft: (isTurningLeft) => set({ isTurningLeft }), - setTurningRight: (isTurningRight) => set({ isTurningRight }), - - setWorldBoundary: (worldBoundary) => set({ worldBoundary }), - - setOtherPlayers: (otherPlayers) => set({ otherPlayers }), - updateOtherPlayer: (id, data) => - set((state) => ({ - otherPlayers: state.otherPlayers.map((p) => - p.id === id ? { ...p, ...data } : p, - ), - })), - - discoverIsland: (id) => { - const { - discoveredIslands, - islands, - expandedIslands, - showcaseIslands, - showcaseUnlocked, - cornersUnlocked, - stage, - unlockedUpgrades: _unlockedUpgrades, - compassTarget, - } = get() - if (!discoveredIslands.has(id)) { - const newDiscovered = new Set(discoveredIslands) - newDiscovered.add(id) - set({ discoveredIslands: newDiscovered }) - - // Clear compass target if this is the target island - if (compassTarget?.id === id) { - set({ compassTarget: null }) - } + ({ setState, get }) => { + const set = (partial: Partial) => + setState((state) => ({ ...state, ...partial })) + + const actions: GameActions = { + setPhase: (phase) => set({ phase }), + setStage: (stage) => set({ stage }), + setBoatType: (boatType) => set({ boatType }), + applyShipUpgrade: (upgrade: Upgrade) => { + const { shipStats, unlockedUpgrades, boatHealth } = get() + // Check if we already have this exact upgrade (same type and tier) + const alreadyHave = unlockedUpgrades.some( + (u) => u.type === upgrade.type && u.tier === upgrade.tier, + ) + if (alreadyHave) return + const newStats = applyUpgrade(shipStats, upgrade) - // Check if all core islands discovered (triggers upgrade in exploration stage) - if (stage === 'exploration' && newDiscovered.size === islands.length) { - // Trigger upgrade sequence instead of complete - get().upgradeToShip() - } + // If maxHealth increased, also heal by that amount + const healthGain = newStats.maxHealth - shipStats.maxHealth + const newHealth = healthGain > 0 ? boatHealth + healthGain : boatHealth - // In battle stage, handle partner/showcase island discoveries - if (stage === 'battle') { - const partnerIsland = expandedIslands.find((i) => i.id === id) - const showcaseIsland = showcaseIslands.find((i) => i.id === id) - - if (partnerIsland && partnerIsland.type === 'partner') { - // Count discovered partner islands - const discoveredPartnerCount = Array.from(newDiscovered).filter( - (discoveredId) => - expandedIslands.some( - (i) => i.id === discoveredId && i.type === 'partner', - ), - ).length - - // Grant next partner upgrade (0-indexed) - const upgradeIndex = discoveredPartnerCount - 1 - const nextUpgrade = PARTNER_UPGRADE_ORDER[upgradeIndex] - if (nextUpgrade) { - get().applyShipUpgrade(nextUpgrade) - set({ lastUnlockedUpgrade: nextUpgrade }) + set({ + shipStats: newStats, + unlockedUpgrades: [...unlockedUpgrades, upgrade], + boatHealth: newHealth, + }) + }, + clearLastUnlockedUpgrade: () => set({ lastUnlockedUpgrade: null }), + + setBoatPosition: (boatPosition) => set({ boatPosition }), + setBoatRotation: (boatRotation) => set({ boatRotation }), + setBoatVelocity: (boatVelocity) => set({ boatVelocity }), + setBoatHealth: (boatHealth) => set({ boatHealth }), + setMovingForward: (isMovingForward) => set({ isMovingForward }), + setMovingBackward: (isMovingBackward) => set({ isMovingBackward }), + setTurningLeft: (isTurningLeft) => set({ isTurningLeft }), + setTurningRight: (isTurningRight) => set({ isTurningRight }), + + setWorldBoundary: (worldBoundary) => set({ worldBoundary }), + + setOtherPlayers: (otherPlayers) => set({ otherPlayers }), + updateOtherPlayer: (id, data) => + setState((state) => ({ + ...state, + otherPlayers: state.otherPlayers.map((p) => + p.id === id ? { ...p, ...data } : p, + ), + })), + + discoverIsland: (id) => { + const { + discoveredIslands, + islands, + expandedIslands, + showcaseIslands, + showcaseUnlocked, + cornersUnlocked, + stage, + unlockedUpgrades: _unlockedUpgrades, + compassTarget, + } = get() + if (!discoveredIslands.has(id)) { + const newDiscovered = new Set(discoveredIslands) + newDiscovered.add(id) + set({ discoveredIslands: newDiscovered }) + + // Clear compass target if this is the target island + if (compassTarget?.id === id) { + set({ compassTarget: null }) } - // Check if all partner islands discovered - unlock showcase - const totalPartnerIslands = expandedIslands.filter( - (i) => i.type === 'partner', - ).length - console.log( - `[Game] Partner discovered: ${discoveredPartnerCount}/${totalPartnerIslands}, showcaseUnlocked: ${showcaseUnlocked}`, - ) + // Check if all core islands discovered (triggers upgrade in exploration stage) if ( - !showcaseUnlocked && - discoveredPartnerCount === totalPartnerIslands + stage === 'exploration' && + newDiscovered.size === islands.length ) { - console.log('[Game] All partners discovered! Unlocking showcase...') - get().unlockShowcase() + // Trigger upgrade sequence instead of complete + actions.upgradeToShip() } - } - if (showcaseIsland && showcaseIsland.type === 'showcase') { - // Count discovered showcase islands (exclude corner islands which also use showcase type) - const realShowcaseIslands = showcaseIslands.filter( - (i) => !i.id.startsWith('corner-'), - ) - const discoveredShowcaseCount = Array.from(newDiscovered).filter( - (discoveredId) => - realShowcaseIslands.some((i) => i.id === discoveredId), - ).length - - // Grant next showcase upgrade (0-indexed) - const upgradeIndex = discoveredShowcaseCount - 1 - const nextUpgrade = SHOWCASE_UPGRADE_ORDER[upgradeIndex] - if (nextUpgrade) { - get().applyShipUpgrade(nextUpgrade) - set({ lastUnlockedUpgrade: nextUpgrade }) + // In battle stage, handle partner/showcase island discoveries + if (stage === 'battle') { + const partnerIsland = expandedIslands.find((i) => i.id === id) + const showcaseIsland = showcaseIslands.find((i) => i.id === id) + + if (partnerIsland && partnerIsland.type === 'partner') { + // Count discovered partner islands + const discoveredPartnerCount = Array.from(newDiscovered).filter( + (discoveredId) => + expandedIslands.some( + (i) => i.id === discoveredId && i.type === 'partner', + ), + ).length + + // Grant next partner upgrade (0-indexed) + const upgradeIndex = discoveredPartnerCount - 1 + const nextUpgrade = PARTNER_UPGRADE_ORDER[upgradeIndex] + if (nextUpgrade) { + actions.applyShipUpgrade(nextUpgrade) + set({ lastUnlockedUpgrade: nextUpgrade }) + } + + // Check if all partner islands discovered - unlock showcase + const totalPartnerIslands = expandedIslands.filter( + (i) => i.type === 'partner', + ).length + console.log( + `[Game] Partner discovered: ${discoveredPartnerCount}/${totalPartnerIslands}, showcaseUnlocked: ${showcaseUnlocked}`, + ) + if ( + !showcaseUnlocked && + discoveredPartnerCount === totalPartnerIslands + ) { + console.log( + '[Game] All partners discovered! Unlocking showcase...', + ) + actions.unlockShowcase() + } + } + + if (showcaseIsland && showcaseIsland.type === 'showcase') { + // Count discovered showcase islands (exclude corner islands which also use showcase type) + const realShowcaseIslands = showcaseIslands.filter( + (i) => !i.id.startsWith('corner-'), + ) + const discoveredShowcaseCount = Array.from(newDiscovered).filter( + (discoveredId) => + realShowcaseIslands.some((i) => i.id === discoveredId), + ).length + + // Grant next showcase upgrade (0-indexed) + const upgradeIndex = discoveredShowcaseCount - 1 + const nextUpgrade = SHOWCASE_UPGRADE_ORDER[upgradeIndex] + if (nextUpgrade) { + actions.applyShipUpgrade(nextUpgrade) + set({ lastUnlockedUpgrade: nextUpgrade }) + } + + // Check if all showcase islands discovered - unlock corners + if ( + !cornersUnlocked && + discoveredShowcaseCount === realShowcaseIslands.length && + realShowcaseIslands.length > 0 + ) { + actions.unlockCorners() + } + } + + // Check if a corner island was discovered + const { cornerIslands, gameWon } = get() + const cornerIsland = cornerIslands.find((i) => i.id === id) + if (cornerIsland && !gameWon) { + // Count discovered corner islands + const discoveredCornerCount = Array.from(newDiscovered).filter( + (discoveredId) => + cornerIslands.some((i) => i.id === discoveredId), + ).length + + // Check if all 4 corners discovered - player wins! + if ( + discoveredCornerCount === cornerIslands.length && + cornerIslands.length === 4 + ) { + set({ gameWon: true }) + } + } } - - // Check if all showcase islands discovered - unlock corners - if ( - !cornersUnlocked && - discoveredShowcaseCount === realShowcaseIslands.length && - realShowcaseIslands.length > 0 - ) { - get().unlockCorners() + } + }, + + setNearbyIsland: (nearbyIsland) => set({ nearbyIsland }), + setDiscoveryProgress: (discoveryProgress) => set({ discoveryProgress }), + + setIslands: (islands) => { + set({ islands }) + // Restore compass target from pending ID if we have one + if (pendingCompassTargetId) { + const target = islands.find((i) => i.id === pendingCompassTargetId) + if (target) { + set({ compassTarget: target }) + pendingCompassTargetId = null } } - - // Check if a corner island was discovered - const { cornerIslands, gameWon } = get() - const cornerIsland = cornerIslands.find((i) => i.id === id) - if (cornerIsland && !gameWon) { - // Count discovered corner islands - const discoveredCornerCount = Array.from(newDiscovered).filter( - (discoveredId) => cornerIslands.some((i) => i.id === discoveredId), - ).length - - // Check if all 4 corners discovered - player wins! - if ( - discoveredCornerCount === cornerIslands.length && - cornerIslands.length === 4 - ) { - set({ gameWon: true }) + }, + setExpandedIslands: (expandedIslands) => { + set({ expandedIslands }) + // Also check expanded islands for compass target + if (pendingCompassTargetId) { + const target = expandedIslands.find( + (i) => i.id === pendingCompassTargetId, + ) + if (target) { + set({ compassTarget: target }) + pendingCompassTargetId = null } } - } - } - }, - - setNearbyIsland: (nearbyIsland) => set({ nearbyIsland }), - setDiscoveryProgress: (discoveryProgress) => set({ discoveryProgress }), - - setIslands: (islands) => { - set({ islands }) - // Restore compass target from pending ID if we have one - if (pendingCompassTargetId) { - const target = islands.find((i) => i.id === pendingCompassTargetId) - if (target) { - set({ compassTarget: target }) - pendingCompassTargetId = null - } - } - }, - setExpandedIslands: (expandedIslands) => { - set({ expandedIslands }) - // Also check expanded islands for compass target - if (pendingCompassTargetId) { - const target = expandedIslands.find( - (i) => i.id === pendingCompassTargetId, - ) - if (target) { - set({ compassTarget: target }) - pendingCompassTargetId = null - } - } - }, - - setShowcaseIslands: (showcaseIslands) => { - set({ showcaseIslands }) - // Check showcase islands for compass target - if (pendingCompassTargetId) { - const target = showcaseIslands.find( - (i) => i.id === pendingCompassTargetId, - ) - if (target) { - set({ compassTarget: target }) - pendingCompassTargetId = null - } - } - }, - - unlockShowcase: () => { - set({ showcaseUnlocked: true }) - }, + }, + + setShowcaseIslands: (showcaseIslands) => { + set({ showcaseIslands }) + // Check showcase islands for compass target + if (pendingCompassTargetId) { + const target = showcaseIslands.find( + (i) => i.id === pendingCompassTargetId, + ) + if (target) { + set({ compassTarget: target }) + pendingCompassTargetId = null + } + } + }, - setCornerIslands: (cornerIslands) => { - set({ cornerIslands }) - }, + unlockShowcase: () => { + set({ showcaseUnlocked: true }) + }, - unlockCorners: () => { - set({ cornersUnlocked: true }) - }, + setCornerIslands: (cornerIslands) => { + set({ cornerIslands }) + }, - setRockColliders: (rockColliders) => set({ rockColliders }), - - setCoins: (coins) => { - // Restore collected state from pending IDs - if (pendingCollectedCoinIds.length > 0) { - const collectedSet = new Set(pendingCollectedCoinIds) - const restoredCoins = coins.map((c) => - collectedSet.has(c.id) ? { ...c, collected: true } : c, - ) - set({ coins: restoredCoins }) - pendingCollectedCoinIds = [] - } else { - set({ coins }) - } - }, + unlockCorners: () => { + set({ cornersUnlocked: true }) + }, - collectCoin: (id) => { - const { coins, coinsCollected } = get() - const coin = coins.find((c) => c.id === id) - if (coin && !coin.collected) { - const newCoins = coins.map((c) => - c.id === id ? { ...c, collected: true, collectedAt: Date.now() } : c, - ) - set({ coins: newCoins, coinsCollected: coinsCollected + 1 }) - } - }, + setRockColliders: (rockColliders) => set({ rockColliders }), - respawnCoins: () => { - const { coins } = get() - const now = Date.now() - const RESPAWN_DELAY = 60000 // 60 seconds to respawn + setCoins: (coins) => { + // Restore collected state from pending IDs + if (pendingCollectedCoinIds.length > 0) { + const collectedSet = new Set(pendingCollectedCoinIds) + const restoredCoins = coins.map((c) => + collectedSet.has(c.id) ? { ...c, collected: true } : c, + ) + set({ coins: restoredCoins }) + pendingCollectedCoinIds = [] + } else { + set({ coins }) + } + }, + + collectCoin: (id) => { + const { coins, coinsCollected } = get() + const coin = coins.find((c) => c.id === id) + if (coin && !coin.collected) { + const newCoins = coins.map((c) => + c.id === id + ? { ...c, collected: true, collectedAt: Date.now() } + : c, + ) + set({ coins: newCoins, coinsCollected: coinsCollected + 1 }) + } + }, - let hasChanges = false - const newCoins = coins.map((c) => { - if (c.collected && c.collectedAt && now - c.collectedAt > RESPAWN_DELAY) { - hasChanges = true - return { ...c, collected: false, collectedAt: undefined } - } - return c - }) + respawnCoins: () => { + const { coins } = get() + const now = Date.now() + const RESPAWN_DELAY = 60000 // 60 seconds to respawn - if (hasChanges) { - set({ coins: newCoins }) - } - }, + let hasChanges = false + const newCoins = coins.map((c) => { + if ( + c.collected && + c.collectedAt && + now - c.collectedAt > RESPAWN_DELAY + ) { + hasChanges = true + return { ...c, collected: false, collectedAt: undefined } + } + return c + }) - toggleMute: () => set((state) => ({ isMuted: !state.isMuted })), + if (hasChanges) { + set({ coins: newCoins }) + } + }, + + toggleMute: () => + setState((state) => ({ + ...state, + isMuted: !state.isMuted, + })), + + setShowCollisionDebug: (show) => set({ showCollisionDebug: show }), + setDebugZoomOut: (zoom) => set({ debugZoomOut: zoom }), + + addKill: () => + setState((state) => ({ + ...state, + kills: state.kills + 1, + })), + addDeath: () => + setState((state) => ({ + ...state, + deaths: state.deaths + 1, + })), + + setBoundaryEdges: (boundaryEdges) => set({ boundaryEdges }), + + fireCannon: () => { + const { + stage, + boatPosition, + boatRotation, + cannonballs, + lastFireTime, + shipStats, + } = get() + if (stage !== 'battle') return + + const now = Date.now() + if (now - lastFireTime < shipStats.sideFireRate) return + + const newCannonballs: Cannonball[] = [] + const cannonOffset = 0.5 + const baseSpeed = 20 * shipStats.cannonRange + + // Helper to create a cannonball + // Ship forward is [sin(rotation), cos(rotation)] + // Ship right (starboard) is [cos(rotation), -sin(rotation)] + const createBall = ( + side: 'right' | 'left', + spreadAngle: number = 0, + ): Cannonball => { + const sideMultiplier = side === 'right' ? 1 : -1 + + // Position: offset perpendicular to ship heading + const perpX = Math.cos(boatRotation) * sideMultiplier + const perpZ = -Math.sin(boatRotation) * sideMultiplier + const fireX = boatPosition[0] + perpX * cannonOffset + const fireZ = boatPosition[2] + perpZ * cannonOffset + + // Velocity: fire perpendicular to ship, with optional spread + const fireAngle = boatRotation + spreadAngle * sideMultiplier + const velX = Math.cos(fireAngle) * baseSpeed * sideMultiplier + const velZ = -Math.sin(fireAngle) * baseSpeed * sideMultiplier + + return { + id: now + Math.random() * 1000, + position: [fireX, 0.5, fireZ], + velocity: [velX, 2, velZ], + ownerId: 'player', + createdAt: now, + } + } - setShowCollisionDebug: (show) => set({ showCollisionDebug: show }), - debugZoomOut: false, - setDebugZoomOut: (zoom) => set({ debugZoomOut: zoom }), - - addKill: () => set((state) => ({ kills: state.kills + 1 })), - addDeath: () => set((state) => ({ deaths: state.deaths + 1 })), - - setBoundaryEdges: (boundaryEdges) => set({ boundaryEdges }), - - fireCannon: () => { - const { - stage, - boatPosition, - boatRotation, - cannonballs, - lastFireTime, - shipStats, - } = get() - if (stage !== 'battle') return - - const now = Date.now() - if (now - lastFireTime < shipStats.sideFireRate) return - - const newCannonballs: Cannonball[] = [] - const cannonOffset = 0.5 - const baseSpeed = 20 * shipStats.cannonRange - - // Helper to create a cannonball - // Ship forward is [sin(rotation), cos(rotation)] - // Ship right (starboard) is [cos(rotation), -sin(rotation)] - const createBall = ( - side: 'right' | 'left', - spreadAngle: number = 0, - ): Cannonball => { - const sideMultiplier = side === 'right' ? 1 : -1 - - // Position: offset perpendicular to ship heading - const perpX = Math.cos(boatRotation) * sideMultiplier - const perpZ = -Math.sin(boatRotation) * sideMultiplier - const fireX = boatPosition[0] + perpX * cannonOffset - const fireZ = boatPosition[2] + perpZ * cannonOffset - - // Velocity: fire perpendicular to ship, with optional spread - const fireAngle = boatRotation + spreadAngle * sideMultiplier - const velX = Math.cos(fireAngle) * baseSpeed * sideMultiplier - const velZ = -Math.sin(fireAngle) * baseSpeed * sideMultiplier - - return { - id: now + Math.random() * 1000, - position: [fireX, 0.5, fireZ], - velocity: [velX, 2, velZ], - ownerId: 'player', - createdAt: now, - } - } + // Fire from right side + newCannonballs.push(createBall('right')) + if (shipStats.doubleShot) { + newCannonballs.push(createBall('right', 0.15)) // Spread shot + } - // Fire from right side - newCannonballs.push(createBall('right')) - if (shipStats.doubleShot) { - newCannonballs.push(createBall('right', 0.15)) // Spread shot - } + // Fire from left side if dual cannons + if (shipStats.dualCannons) { + newCannonballs.push(createBall('left')) + if (shipStats.doubleShot) { + newCannonballs.push(createBall('left', 0.15)) + } + } - // Fire from left side if dual cannons - if (shipStats.dualCannons) { - newCannonballs.push(createBall('left')) - if (shipStats.doubleShot) { - newCannonballs.push(createBall('left', 0.15)) - } - } + set({ + cannonballs: [...cannonballs, ...newCannonballs], + lastFireTime: now, + }) + }, + + // Gatling gun fire (forward facing, rapid) + fireGatling: () => { + const { + stage, + boatPosition, + boatRotation, + cannonballs, + shipStats, + lastGatlingTime, + } = get() + if (stage !== 'battle' || !shipStats.gatlingGuns) return + + const now = Date.now() + if (now - lastGatlingTime < shipStats.frontFireRate) return + + // Fire forward + const speed = 35 + const velX = Math.sin(boatRotation) * speed + const velZ = Math.cos(boatRotation) * speed + + // Slight spread + const spread = (Math.random() - 0.5) * 0.1 + + const newBall: Cannonball = { + id: now + Math.random() * 1000, + position: [boatPosition[0], 0.4, boatPosition[2]], + velocity: [velX + spread * speed, 0.5, velZ + spread * speed], + ownerId: 'player', + createdAt: now, + isGatling: true, + } - set({ - cannonballs: [...cannonballs, ...newCannonballs], - lastFireTime: now, - }) - }, + set({ + cannonballs: [...cannonballs, newBall], + lastGatlingTime: now, + }) + }, - // Gatling gun fire (forward facing, rapid) - fireGatling: () => { - const { - stage, - boatPosition, - boatRotation, - cannonballs, - shipStats, - lastGatlingTime, - } = get() - if (stage !== 'battle' || !shipStats.gatlingGuns) return - - const now = Date.now() - if (now - lastGatlingTime < shipStats.frontFireRate) return - - // Fire forward - const speed = 35 - const velX = Math.sin(boatRotation) * speed - const velZ = Math.cos(boatRotation) * speed - - // Slight spread - const spread = (Math.random() - 0.5) * 0.1 - - const newBall: Cannonball = { - id: now + Math.random() * 1000, - position: [boatPosition[0], 0.4, boatPosition[2]], - velocity: [velX + spread * speed, 0.5, velZ + spread * speed], - ownerId: 'player', - createdAt: now, - isGatling: true, - } + updateCannonballs: (cannonballs) => set({ cannonballs }), - set({ - cannonballs: [...cannonballs, newBall], - lastGatlingTime: now, - }) - }, + removeCannonball: (id) => + setState((state) => ({ + ...state, + cannonballs: state.cannonballs.filter((c) => c.id !== id), + })), - updateCannonballs: (cannonballs) => set({ cannonballs }), - - removeCannonball: (id) => - set((state) => ({ - cannonballs: state.cannonballs.filter((c) => c.id !== id), - })), - - upgradeToShip: () => { - set({ - phase: 'upgrading', - // boatType stays 'dinghy' until user clicks "Set Sail" - stage: 'battle', - worldBoundary: EXPANDED_WORLD_BOUNDARY, - boatHealth: 100, - }) - // User must click button to continue - no auto timeout - }, + upgradeToShip: () => { + set({ + phase: 'upgrading', + // boatType stays 'dinghy' until user clicks "Set Sail" + stage: 'battle', + worldBoundary: EXPANDED_WORLD_BOUNDARY, + boatHealth: 100, + }) + // User must click button to continue - no auto timeout + }, + + // Shop actions + openShop: () => set({ isShopOpen: true }), + closeShop: () => set({ isShopOpen: false }), + + purchaseItem: (itemType) => { + const { + coinsCollected, + stage, + boatHealth, + shipStats, + islands, + expandedIslands, + discoveredIslands, + purchasedBoosts, + } = get() + const item = SHOP_ITEMS.find((i) => i.type === itemType) + + if (!item) return false + if (coinsCollected < item.cost) return false + if (!item.stages.includes(stage)) return false + + // Check max stacks for stackable items + if (item.stackable && item.maxStacks && item.maxStacks > 0) { + const currentStacks = + itemType === 'permSpeed' + ? purchasedBoosts.permSpeed + : itemType === 'permAccel' + ? purchasedBoosts.permAccel + : 0 + if (currentStacks >= item.maxStacks) return false + } - // Shop actions - openShop: () => set({ isShopOpen: true }), - closeShop: () => set({ isShopOpen: false }), - - purchaseItem: (itemType) => { - const { - coinsCollected, - stage, - boatHealth, - shipStats, - islands, - expandedIslands, - discoveredIslands, - purchasedBoosts, - } = get() - const item = SHOP_ITEMS.find((i) => i.type === itemType) - - if (!item) return false - if (coinsCollected < item.cost) return false - if (!item.stages.includes(stage)) return false - - // Check max stacks for stackable items - if (item.stackable && item.maxStacks && item.maxStacks > 0) { - const currentStacks = - itemType === 'permSpeed' - ? purchasedBoosts.permSpeed - : itemType === 'permAccel' - ? purchasedBoosts.permAccel - : 0 - if (currentStacks >= item.maxStacks) return false - } + // Check if non-stackable item already owned + if (itemType === 'rapidFire' && purchasedBoosts.rapidFire) return false + + // Deduct coins + set({ coinsCollected: coinsCollected - item.cost }) + + switch (itemType) { + case 'compass': { + // Find a random undiscovered island + const allIslands = + stage === 'battle' ? [...islands, ...expandedIslands] : islands + const undiscovered = allIslands.filter( + (i) => !discoveredIslands.has(i.id), + ) + if (undiscovered.length > 0) { + // Pick random (not nearest) + const randomIndex = Math.floor( + Math.random() * undiscovered.length, + ) + set({ compassTarget: undiscovered[randomIndex] }) + } + break + } + case 'speedBoost': { + // 10 second speed boost + set({ speedBoostEndTime: Date.now() + 10000 }) + break + } + case 'healthPack': { + // Restore 50 health, up to max (including purchased health boosts) + const maxHealth = + shipStats.maxHealth + purchasedBoosts.permHealth * 25 + const newHealth = Math.min(boatHealth + 50, maxHealth) + set({ boatHealth: newHealth }) + break + } + case 'permSpeed': { + // Permanent +10% speed boost + set({ + purchasedBoosts: { + ...purchasedBoosts, + permSpeed: purchasedBoosts.permSpeed + 1, + }, + }) + break + } + case 'permAccel': { + // Permanent +15% acceleration boost + set({ + purchasedBoosts: { + ...purchasedBoosts, + permAccel: purchasedBoosts.permAccel + 1, + }, + }) + break + } + case 'permHealth': { + // Permanent +25 max health boost + const newPermHealth = purchasedBoosts.permHealth + 1 + const healthBonus = 25 // Each purchase adds 25 max health + set({ + purchasedBoosts: { + ...purchasedBoosts, + permHealth: newPermHealth, + }, + // Also increase current health by the bonus amount + boatHealth: boatHealth + healthBonus, + }) + break + } + case 'rapidFire': { + // Unlock auto-loader (rapid fire side cannons) + set({ + purchasedBoosts: { + ...purchasedBoosts, + rapidFire: true, + }, + }) + break + } + } - // Check if non-stackable item already owned - if (itemType === 'rapidFire' && purchasedBoosts.rapidFire) return false + set({ isShopOpen: false }) + return true + }, - // Deduct coins - set({ coinsCollected: coinsCollected - item.cost }) + setCompassTarget: (island) => set({ compassTarget: island }), - switch (itemType) { - case 'compass': { - // Find a random undiscovered island - const allIslands = - stage === 'battle' ? [...islands, ...expandedIslands] : islands - const undiscovered = allIslands.filter( - (i) => !discoveredIslands.has(i.id), - ) - if (undiscovered.length > 0) { - // Pick random (not nearest) - const randomIndex = Math.floor(Math.random() * undiscovered.length) - set({ compassTarget: undiscovered[randomIndex] }) + clearCompassOnDiscover: (islandId) => { + const { compassTarget } = get() + if (compassTarget?.id === islandId) { + set({ compassTarget: null }) } - break - } - case 'speedBoost': { - // 10 second speed boost - set({ speedBoostEndTime: Date.now() + 10000 }) - break - } - case 'healthPack': { - // Restore 50 health, up to max (including purchased health boosts) - const maxHealth = shipStats.maxHealth + purchasedBoosts.permHealth * 25 - const newHealth = Math.min(boatHealth + 50, maxHealth) - set({ boatHealth: newHealth }) - break - } - case 'permSpeed': { - // Permanent +10% speed boost - set({ - purchasedBoosts: { - ...purchasedBoosts, - permSpeed: purchasedBoosts.permSpeed + 1, - }, - }) - break - } - case 'permAccel': { - // Permanent +15% acceleration boost - set({ - purchasedBoosts: { - ...purchasedBoosts, - permAccel: purchasedBoosts.permAccel + 1, - }, - }) - break - } - case 'permHealth': { - // Permanent +25 max health boost - const newPermHealth = purchasedBoosts.permHealth + 1 - const healthBonus = 25 // Each purchase adds 25 max health + }, + + reset: () => set({ - purchasedBoosts: { - ...purchasedBoosts, - permHealth: newPermHealth, - }, - // Also increase current health by the bonus amount - boatHealth: boatHealth + healthBonus, - }) - break - } - case 'rapidFire': { - // Unlock auto-loader (rapid fire side cannons) + ...initialState, + islands: get().islands, + expandedIslands: get().expandedIslands, + rockColliders: get().rockColliders, + coins: get().coins.map((c) => ({ ...c, collected: false })), + discoveredIslands: new Set(), + kills: 0, + deaths: 0, + }), + + startOver: () => { + // Clear localStorage + localStorage.removeItem(STORAGE_KEY) + // Full reset set({ - purchasedBoosts: { - ...purchasedBoosts, - rapidFire: true, - }, + ...initialState, + islands: get().islands, + expandedIslands: [], // Clear expanded islands + showcaseIslands: [], // Clear showcase islands + cornerIslands: [], // Clear corner islands + showcaseUnlocked: false, + cornersUnlocked: false, + gameWon: false, + rockColliders: get().rockColliders, + coins: get().coins.map((c) => ({ ...c, collected: false })), + discoveredIslands: new Set(), }) - break - } - } - - set({ isShopOpen: false }) - return true - }, - - setCompassTarget: (island) => set({ compassTarget: island }), + }, + + restartBattle: () => { + const { + islands, + expandedIslands, + showcaseIslands, + cornerIslands, + showcaseUnlocked, + cornersUnlocked, + rockColliders, + coins, + discoveredIslands, + unlockedUpgrades, + shipStats, + purchasedBoosts, + boatPosition, + } = get() + + // World boundary depends on showcase unlock status + const worldBoundary = showcaseUnlocked ? 520 : EXPANDED_WORLD_BOUNDARY + + // Find nearest discovered island to respawn at + const allIslands = [ + ...islands, + ...expandedIslands, + ...showcaseIslands, + ...cornerIslands, + ] + const discoveredIslandsList = allIslands.filter((i) => + discoveredIslands.has(i.id), + ) - clearCompassOnDiscover: (islandId) => { - const { compassTarget } = get() - if (compassTarget?.id === islandId) { - set({ compassTarget: null }) - } - }, + let spawnPosition: [number, number, number] = [0, 0, 0] + if (discoveredIslandsList.length > 0) { + // Find nearest discovered island to death position + let nearestIsland = discoveredIslandsList[0] + let nearestDist = Infinity + for (const island of discoveredIslandsList) { + const dx = island.position[0] - boatPosition[0] + const dz = island.position[2] - boatPosition[2] + const dist = dx * dx + dz * dz + if (dist < nearestDist) { + nearestDist = dist + nearestIsland = island + } + } + // Spawn slightly away from the island (not inside it) + const spawnOffset = 8 + const angle = Math.random() * Math.PI * 2 + spawnPosition = [ + nearestIsland.position[0] + Math.cos(angle) * spawnOffset, + 0, + nearestIsland.position[2] + Math.sin(angle) * spawnOffset, + ] + } - reset: () => - set({ - ...initialState, - islands: get().islands, - expandedIslands: get().expandedIslands, - rockColliders: get().rockColliders, - coins: get().coins.map((c) => ({ ...c, collected: false })), - discoveredIslands: new Set(), - kills: 0, - deaths: 0, - }), - - startOver: () => { - // Clear localStorage - localStorage.removeItem(STORAGE_KEY) - // Full reset - set({ - ...initialState, - islands: get().islands, - expandedIslands: [], // Clear expanded islands - showcaseIslands: [], // Clear showcase islands - cornerIslands: [], // Clear corner islands - showcaseUnlocked: false, - cornersUnlocked: false, - gameWon: false, - rockColliders: get().rockColliders, - coins: get().coins.map((c) => ({ ...c, collected: false })), - discoveredIslands: new Set(), - }) - }, + // Calculate total max health (upgrades + purchased boosts) + const totalMaxHealth = + shipStats.maxHealth + purchasedBoosts.permHealth * 25 - restartBattle: () => { - const { - islands, - expandedIslands, - showcaseIslands, - cornerIslands, - showcaseUnlocked, - cornersUnlocked, - rockColliders, - coins, - discoveredIslands, - unlockedUpgrades, - shipStats, - purchasedBoosts, - boatPosition, - } = get() - - // World boundary depends on showcase unlock status - const worldBoundary = showcaseUnlocked ? 520 : EXPANDED_WORLD_BOUNDARY - - // Find nearest discovered island to respawn at - const allIslands = [ - ...islands, - ...expandedIslands, - ...showcaseIslands, - ...cornerIslands, - ] - const discoveredIslandsList = allIslands.filter((i) => - discoveredIslands.has(i.id), - ) - - let spawnPosition: [number, number, number] = [0, 0, 0] - if (discoveredIslandsList.length > 0) { - // Find nearest discovered island to death position - let nearestIsland = discoveredIslandsList[0] - let nearestDist = Infinity - for (const island of discoveredIslandsList) { - const dx = island.position[0] - boatPosition[0] - const dz = island.position[2] - boatPosition[2] - const dist = dx * dx + dz * dz - if (dist < nearestDist) { - nearestDist = dist - nearestIsland = island - } - } - // Spawn slightly away from the island (not inside it) - const spawnOffset = 8 - const angle = Math.random() * Math.PI * 2 - spawnPosition = [ - nearestIsland.position[0] + Math.cos(angle) * spawnOffset, - 0, - nearestIsland.position[2] + Math.sin(angle) * spawnOffset, - ] + set({ + phase: 'playing', + stage: 'battle', + boatType: 'ship', + boatPosition: spawnPosition, + boatRotation: 0, + boatVelocity: 0, + boatHealth: totalMaxHealth, + isMovingForward: false, + isMovingBackward: false, + isTurningLeft: false, + isTurningRight: false, + worldBoundary, + otherPlayers: [], + cannonballs: [], + lastFireTime: 0, + lastGatlingTime: 0, + compassTarget: null, + speedBoostEndTime: null, + nearbyIsland: null, + discoveryProgress: 0, + coinsCollected: get().coinsCollected, // Keep all coins on death + // Keep these + islands, + expandedIslands, + showcaseIslands, + cornerIslands, + showcaseUnlocked, + cornersUnlocked, + rockColliders, + coins: coins.map((c) => ({ ...c, collected: false })), // Respawn all coins + discoveredIslands, + unlockedUpgrades, + shipStats, + purchasedBoosts, + }) + }, } - // Calculate total max health (upgrades + purchased boosts) - const totalMaxHealth = shipStats.maxHealth + purchasedBoosts.permHealth * 25 - - set({ - phase: 'playing', - stage: 'battle', - boatType: 'ship', - boatPosition: spawnPosition, - boatRotation: 0, - boatVelocity: 0, - boatHealth: totalMaxHealth, - isMovingForward: false, - isMovingBackward: false, - isTurningLeft: false, - isTurningRight: false, - worldBoundary, - otherPlayers: [], - cannonballs: [], - lastFireTime: 0, - lastGatlingTime: 0, - compassTarget: null, - speedBoostEndTime: null, - nearbyIsland: null, - discoveryProgress: 0, - coinsCollected: get().coinsCollected, // Keep all coins on death - // Keep these - islands, - expandedIslands, - showcaseIslands, - cornerIslands, - showcaseUnlocked, - cornersUnlocked, - rockColliders, - coins: coins.map((c) => ({ ...c, collected: false })), // Respawn all coins - discoveredIslands, - unlockedUpgrades, - shipStats, - purchasedBoosts, - }) + return actions }, -})) +) export function useGamePersistence() { useEffect(() => { const persist = () => { - const state = useGameStore.getState() + const state = gameStore.state saveToLocalStorage(extractPersistedState(state)) } const interval = window.setInterval(() => { - const state = useGameStore.getState() + const state = gameStore.state if (state.phase === 'playing' || state.phase === 'gameover') { saveToLocalStorage(extractPersistedState(state)) } diff --git a/src/components/game/machines/GameMachineProvider.tsx b/src/components/game/machines/GameMachineProvider.tsx index 646f18605..abb2c9455 100644 --- a/src/components/game/machines/GameMachineProvider.tsx +++ b/src/components/game/machines/GameMachineProvider.tsx @@ -1,3 +1,4 @@ +import { useSelector } from '@tanstack/react-store' import { createContext, useContext, useEffect, type ReactNode } from 'react' import { useMachine } from '@xstate/react' import { @@ -7,7 +8,7 @@ import { BADGE_INFO, type BadgeTier, } from './progressionMachine' -import { useGameStore } from '../hooks/useGameStore' +import { gameStore } from '../hooks/useGameStore' interface ProgressionContextValue { // Machine state @@ -36,7 +37,7 @@ interface ProgressionContextValue { dismissBadge: () => void reset: () => void - // Discovery actions (called by zustand sync) + // Discovery actions (called by game store sync) discoverLibrary: () => void discoverPartner: () => void discoverShowcase: () => void @@ -48,11 +49,11 @@ const ProgressionContext = createContext(null) export function GameMachineProvider({ children }: { children: ReactNode }) { const [state, send] = useMachine(progressionMachine) - // Get island counts from zustand - const islands = useGameStore((s) => s.islands) - const expandedIslands = useGameStore((s) => s.expandedIslands) - const showcaseIslands = useGameStore((s) => s.showcaseIslands) - const cornerIslands = useGameStore((s) => s.cornerIslands) + // Get island counts from the game store + const islands = useSelector(gameStore, (s) => s.islands) + const expandedIslands = useSelector(gameStore, (s) => s.expandedIslands) + const showcaseIslands = useSelector(gameStore, (s) => s.showcaseIslands) + const cornerIslands = useSelector(gameStore, (s) => s.cornerIslands) // Sync island totals when they change useEffect(() => { @@ -85,15 +86,15 @@ export function GameMachineProvider({ children }: { children: ReactNode }) { send, ]) - // Sync with zustand phase changes (for backward compatibility) - const zustandPhase = useGameStore((s) => s.phase) - const zustandStage = useGameStore((s) => s.stage) - const zustandShowcaseUnlocked = useGameStore((s) => s.showcaseUnlocked) - const zustandCornersUnlocked = useGameStore((s) => s.cornersUnlocked) - const zustandGameWon = useGameStore((s) => s.gameWon) - const discoveredIslands = useGameStore((s) => s.discoveredIslands) + // Sync with game store phase changes (for backward compatibility) + const gamePhase = useSelector(gameStore, (s) => s.phase) + const gameStage = useSelector(gameStore, (s) => s.stage) + const gameShowcaseUnlocked = useSelector(gameStore, (s) => s.showcaseUnlocked) + const gameCornersUnlocked = useSelector(gameStore, (s) => s.cornersUnlocked) + const gameWon = useSelector(gameStore, (s) => s.gameWon) + const discoveredIslands = useSelector(gameStore, (s) => s.discoveredIslands) - // Restore progress from zustand on mount + // Restore progress from the game store on mount useEffect(() => { // Count discovered by type let librariesDiscovered = 0 @@ -108,12 +109,12 @@ export function GameMachineProvider({ children }: { children: ReactNode }) { else if (id.startsWith('corner-')) cornersDiscovered++ } - // Determine highest badge from zustand state + // Determine highest badge from game store state let highestBadge: BadgeTier = 'none' - if (zustandGameWon) highestBadge = 'conqueror' - else if (zustandCornersUnlocked) highestBadge = 'champion' - else if (zustandShowcaseUnlocked) highestBadge = 'adventurer' - else if (zustandStage === 'battle') highestBadge = 'explorer' + if (gameWon) highestBadge = 'conqueror' + else if (gameCornersUnlocked) highestBadge = 'champion' + else if (gameShowcaseUnlocked) highestBadge = 'adventurer' + else if (gameStage === 'battle') highestBadge = 'explorer' // Only restore if we have progress if (highestBadge !== 'none' || librariesDiscovered > 0) { @@ -129,15 +130,15 @@ export function GameMachineProvider({ children }: { children: ReactNode }) { // eslint-disable-next-line react-hooks/exhaustive-deps }, []) // Only on mount - // Sync zustand phase changes to machine (when zustand is source of truth) + // Sync game store phase changes to machine (when the game store is source of truth) useEffect(() => { const machinePhase = getPhaseFromState(state.value) // Sync gameover state - if (zustandPhase === 'gameover' && machinePhase !== 'gameover') { + if (gamePhase === 'gameover' && machinePhase !== 'gameover') { send({ type: 'SHIP_DESTROYED' }) } - }, [zustandPhase, state.value, send]) + }, [gamePhase, state.value, send]) const phase = getPhaseFromState(state.value) const battlePhase = getBattlePhase(state.value) diff --git a/src/components/game/machines/ProgressionSync.tsx b/src/components/game/machines/ProgressionSync.tsx index 2a68be49b..a4b2365d9 100644 --- a/src/components/game/machines/ProgressionSync.tsx +++ b/src/components/game/machines/ProgressionSync.tsx @@ -1,7 +1,7 @@ import { useProgressionSync } from './useProgressionSync' /** - * Component that syncs zustand game state with the progression state machine. + * Component that syncs game store state with the progression state machine. * Must be rendered inside GameMachineProvider. */ export function ProgressionSync() { diff --git a/src/components/game/machines/useProgressionSync.ts b/src/components/game/machines/useProgressionSync.ts index 39a231391..d958f77a9 100644 --- a/src/components/game/machines/useProgressionSync.ts +++ b/src/components/game/machines/useProgressionSync.ts @@ -1,11 +1,12 @@ +import { useSelector } from '@tanstack/react-store' import { useEffect, useRef } from 'react' -import { useGameStore } from '../hooks/useGameStore' +import { gameStore } from '../hooks/useGameStore' import { useProgression } from './GameMachineProvider' /** - * Hook that syncs zustand game state with the progression state machine. + * Hook that syncs game store state with the progression state machine. * This bridge allows the progression machine to track badge state while - * zustand remains the source of truth for game logic. + * the game store remains the source of truth for game logic. */ export function useProgressionSync() { const { @@ -23,13 +24,13 @@ export function useProgressionSync() { const prevDiscoveredRef = useRef>(new Set()) const prevPhaseRef = useRef('') - // Get zustand state - const discoveredIslands = useGameStore((s) => s.discoveredIslands) - const phase = useGameStore((s) => s.phase) - const islands = useGameStore((s) => s.islands) - const expandedIslands = useGameStore((s) => s.expandedIslands) - const showcaseIslands = useGameStore((s) => s.showcaseIslands) - const cornerIslands = useGameStore((s) => s.cornerIslands) + // Get game store state + const discoveredIslands = useSelector(gameStore, (s) => s.discoveredIslands) + const phase = useSelector(gameStore, (s) => s.phase) + const islands = useSelector(gameStore, (s) => s.islands) + const expandedIslands = useSelector(gameStore, (s) => s.expandedIslands) + const showcaseIslands = useSelector(gameStore, (s) => s.showcaseIslands) + const cornerIslands = useSelector(gameStore, (s) => s.cornerIslands) // Sync discoveries useEffect(() => { diff --git a/src/components/game/ui/CompassIndicator.tsx b/src/components/game/ui/CompassIndicator.tsx index 534e13402..9f952a1a1 100644 --- a/src/components/game/ui/CompassIndicator.tsx +++ b/src/components/game/ui/CompassIndicator.tsx @@ -1,8 +1,10 @@ +import { useSelector } from '@tanstack/react-store' import { useEffect, useState } from 'react' -import { useGameStore } from '../hooks/useGameStore' +import { gameStore } from '../hooks/useGameStore' export function CompassIndicator() { - const { phase, compassTarget } = useGameStore() + const phase = useSelector(gameStore, (s) => s.phase) + const compassTarget = useSelector(gameStore, (s) => s.compassTarget) const [indicator, setIndicator] = useState<{ screenX: number screenY: number @@ -18,7 +20,7 @@ export function CompassIndicator() { } const interval = setInterval(() => { - const { boatPosition, compassTarget } = useGameStore.getState() + const { boatPosition, compassTarget } = gameStore.state if (!compassTarget) { setIndicator(null) return diff --git a/src/components/game/ui/CompleteOverlay.tsx b/src/components/game/ui/CompleteOverlay.tsx index 6a8995ab4..4589b5768 100644 --- a/src/components/game/ui/CompleteOverlay.tsx +++ b/src/components/game/ui/CompleteOverlay.tsx @@ -1,5 +1,6 @@ +import { useSelector } from '@tanstack/react-store' import { Link } from '@tanstack/react-router' -import { useGameStore } from '../hooks/useGameStore' +import { gameStore } from '../hooks/useGameStore' import { TrophyIcon, ArrowCounterClockwiseIcon, @@ -7,7 +8,8 @@ import { } from '@phosphor-icons/react' export function CompleteOverlay() { - const { phase, reset, setPhase } = useGameStore() + const phase = useSelector(gameStore, (s) => s.phase) + const { reset, setPhase } = gameStore.actions if (phase !== 'complete') return null diff --git a/src/components/game/ui/DebugPanel.tsx b/src/components/game/ui/DebugPanel.tsx index f03fec78f..c367e766a 100644 --- a/src/components/game/ui/DebugPanel.tsx +++ b/src/components/game/ui/DebugPanel.tsx @@ -1,6 +1,7 @@ +import { useSelector } from '@tanstack/react-store' import { useState, useEffect } from 'react' import { useQuery } from '@tanstack/react-query' -import { useGameStore } from '../hooks/useGameStore' +import { gameStore } from '../hooks/useGameStore' import { PARTNER_UPGRADE_ORDER, SHOWCASE_UPGRADE_ORDER, @@ -31,31 +32,29 @@ export function DebugPanel() { } }, [canAccess]) - const { - phase, - stage, - islands: _islands, - expandedIslands, - showcaseIslands, - showcaseUnlocked, - cornersUnlocked, - cornerIslands: _cornerIslands, - coins: _coins, - discoveredIslands, - coinsCollected: _coinsCollected, - unlockedUpgrades: _unlockedUpgrades, - shipStats: _shipStats, - boatHealth: _boatHealth, - showCollisionDebug, - setShowCollisionDebug, - debugZoomOut, - setDebugZoomOut, - } = useGameStore() + const phase = useSelector(gameStore, (s) => s.phase) + const stage = useSelector(gameStore, (s) => s.stage) + const _islands = useSelector(gameStore, (s) => s.islands) + const expandedIslands = useSelector(gameStore, (s) => s.expandedIslands) + const showcaseIslands = useSelector(gameStore, (s) => s.showcaseIslands) + const showcaseUnlocked = useSelector(gameStore, (s) => s.showcaseUnlocked) + const cornersUnlocked = useSelector(gameStore, (s) => s.cornersUnlocked) + const _cornerIslands = useSelector(gameStore, (s) => s.cornerIslands) + const _coins = useSelector(gameStore, (s) => s.coins) + const discoveredIslands = useSelector(gameStore, (s) => s.discoveredIslands) + const _coinsCollected = useSelector(gameStore, (s) => s.coinsCollected) + const _unlockedUpgrades = useSelector(gameStore, (s) => s.unlockedUpgrades) + const _shipStats = useSelector(gameStore, (s) => s.shipStats) + const _boatHealth = useSelector(gameStore, (s) => s.boatHealth) + const showCollisionDebug = useSelector(gameStore, (s) => s.showCollisionDebug) + const debugZoomOut = useSelector(gameStore, (s) => s.debugZoomOut) + const { setShowCollisionDebug, setDebugZoomOut } = gameStore.actions if (!canAccess) return null const discoverAllIslands = () => { - const { islands, discoverIsland } = useGameStore.getState() + const { islands } = gameStore.state + const { discoverIsland } = gameStore.actions // Discover all but don't trigger upgrade (skip last one) islands.slice(0, -1).forEach((island) => { discoverIsland(island.id) @@ -63,7 +62,8 @@ export function DebugPanel() { } const discoverLastIsland = () => { - const { islands, discoverIsland } = useGameStore.getState() + const { islands } = gameStore.state + const { discoverIsland } = gameStore.actions const lastIsland = islands[islands.length - 1] if (lastIsland) { discoverIsland(lastIsland.id) @@ -71,7 +71,8 @@ export function DebugPanel() { } const collectCoins = (count: number) => { - const { coins, collectCoin } = useGameStore.getState() + const { coins } = gameStore.state + const { collectCoin } = gameStore.actions const uncollected = coins.filter((c) => !c.collected) uncollected.slice(0, count).forEach((coin) => { collectCoin(coin.id) @@ -79,21 +80,22 @@ export function DebugPanel() { } const skipToPlaying = () => { - useGameStore.setState({ phase: 'playing' }) + gameStore.setState((state) => ({ ...state, phase: 'playing' })) } const skipToBattle = () => { - useGameStore.setState({ + gameStore.setState((state) => ({ + ...state, phase: 'playing', stage: 'battle', boatType: 'ship', worldBoundary: 180, - }) + })) } const discoverNextPartner = () => { - const { expandedIslands, discoveredIslands, discoverIsland } = - useGameStore.getState() + const { expandedIslands, discoveredIslands } = gameStore.state + const { discoverIsland } = gameStore.actions const partnerIslands = expandedIslands.filter((i) => i.type === 'partner') const undiscovered = partnerIslands.find( (i) => !discoveredIslands.has(i.id), @@ -104,7 +106,8 @@ export function DebugPanel() { } const discoverAllPartners = () => { - const { expandedIslands, discoverIsland } = useGameStore.getState() + const { expandedIslands } = gameStore.state + const { discoverIsland } = gameStore.actions const partnerIslands = expandedIslands.filter((i) => i.type === 'partner') partnerIslands.forEach((island) => { discoverIsland(island.id) @@ -112,8 +115,8 @@ export function DebugPanel() { } const discoverNextShowcase = () => { - const { showcaseIslands, discoveredIslands, discoverIsland } = - useGameStore.getState() + const { showcaseIslands, discoveredIslands } = gameStore.state + const { discoverIsland } = gameStore.actions const undiscovered = showcaseIslands.find( (i) => !discoveredIslands.has(i.id), ) @@ -123,8 +126,8 @@ export function DebugPanel() { } const discoverNextCorner = () => { - const { cornerIslands, discoveredIslands, discoverIsland } = - useGameStore.getState() + const { cornerIslands, discoveredIslands } = gameStore.state + const { discoverIsland } = gameStore.actions const undiscovered = cornerIslands.find((i) => !discoveredIslands.has(i.id)) if (undiscovered) { discoverIsland(undiscovered.id) @@ -132,35 +135,42 @@ export function DebugPanel() { } const discoverAllCorners = () => { - const { cornerIslands, discoverIsland } = useGameStore.getState() + const { cornerIslands } = gameStore.state + const { discoverIsland } = gameStore.actions cornerIslands.forEach((island) => { discoverIsland(island.id) }) } const grantNextUpgrade = () => { - const { unlockedUpgrades, applyShipUpgrade } = useGameStore.getState() + const { unlockedUpgrades } = gameStore.state + const { applyShipUpgrade } = gameStore.actions const nextUpgrade = UPGRADE_ORDER[unlockedUpgrades.length] if (nextUpgrade) { applyShipUpgrade(nextUpgrade) - useGameStore.setState({ lastUnlockedUpgrade: nextUpgrade }) + gameStore.setState((state) => ({ + ...state, + lastUnlockedUpgrade: nextUpgrade, + })) } } const grantAllUpgrades = () => { - const { applyShipUpgrade } = useGameStore.getState() + const { applyShipUpgrade } = gameStore.actions UPGRADE_ORDER.forEach((upgrade) => { applyShipUpgrade(upgrade) }) } const takeDamage = (amount: number) => { - const { boatHealth, setBoatHealth } = useGameStore.getState() + const { boatHealth } = gameStore.state + const { setBoatHealth } = gameStore.actions setBoatHealth(Math.max(0, boatHealth - amount)) } const healFull = () => { - const { shipStats, setBoatHealth } = useGameStore.getState() + const { shipStats } = gameStore.state + const { setBoatHealth } = gameStore.actions setBoatHealth(shipStats.maxHealth) } @@ -313,7 +323,7 @@ export function DebugPanel() {