Skip to content
Source
Sign inSign up
TanStack/cli
Open History to see the last commit

project.ts

380 lines10.3 KB

1import { useCallback, useEffect, useMemo } from 'react'
2import { create } from 'zustand'
3import { persist } from 'zustand/middleware'
4import { useQuery } from '@tanstack/react-query'
5​
6import { dryRunAddToApp, dryRunCreateApp, loadInitialData } from '../lib/api'
7​
8import { getAddOnStatus } from './add-ons'
9​
10import type { SerializedOptions } from '@tanstack/create'
11​
12import type { AddOnInfo, DryRunOutput, StarterInfo } from '../types'
13​
14export const useProjectOptions = create<
15 SerializedOptions & { initialized: boolean }
16>(() => ({
17 initialized: false,
18 framework: '',
19 mode: '',
20 projectName: '',
21 targetDir: '',
22 typescript: true,
23 tailwind: true,
24 git: true,
25 chosenAddOns: [],
26 addOnOptions: {},
27 packageManager: 'pnpm',
28}))
29​
30const useInitialData = () =>
31 useQuery({
32 queryKey: ['initial-data'],
33 queryFn: loadInitialData,
34 })
35​
36export const useReady = () => {
37 const { data } = useInitialData()
38 return data !== undefined
40​
41const useForcedRouterMode = () => useInitialData().data?.forcedRouterMode
42const useForcedAddOns = () => useInitialData().data?.forcedAddOns
43​
44export const useRegistry = () => useInitialData().data?.registry
45export const useProjectLocalFiles = () => useInitialData().data?.localFiles
46export const useOriginalOutput = () => useInitialData().data?.output
47export const useOriginalOptions = () => useInitialData().data?.options
48export const useOriginalSelectedAddOns = () =>
49 useOriginalOptions()?.chosenAddOns
50export const useApplicationMode = () => useInitialData().data?.applicationMode
51export const useShowDeploymentOptions = () =>
52 useInitialData().data?.showDeploymentOptions
53export const useAddOnsByMode = () => useInitialData().data?.addOns
54export const useSupportedModes = () => useInitialData().data?.supportedModes
55​
56const useApplicationSettings = create<{
57 includeFiles: Array<string>
58}>(() => ({
59 includeFiles: ['unchanged', 'added', 'modified', 'deleted', 'overwritten'],
60}))
61​
62const useMutableAddOns = create<{
63 userSelectedAddOns: Array<string>
64 customAddOns: Array<AddOnInfo>
65}>(() => ({
66 userSelectedAddOns: [],
67 customAddOns: [],
68}))
69​
70export const useProjectStarter = create<{
71 projectStarter: StarterInfo | undefined
72}>(() => ({
73 projectStarter: undefined,
74}))
75​
76export function addCustomAddOn(addOn: AddOnInfo) {
77 useMutableAddOns.setState((state) => ({
78 customAddOns: [...state.customAddOns, addOn],
79 }))
80 if (addOn.modes.includes(useProjectOptions.getState().mode)) {
81 useMutableAddOns.setState((state) => ({
82 userSelectedAddOns: [...state.userSelectedAddOns, addOn.id],
83 }))
84 }
86​
87export function useAddOns() {
88 const ready = useReady()
89​
90 const routerMode = useRouterMode()
91 const originalSelectedAddOns = useOriginalSelectedAddOns()
92 const addOnsByMode = useAddOnsByMode()
93 const forcedAddOns = useForcedAddOns()
94 const { userSelectedAddOns, customAddOns } = useMutableAddOns()
95 const projectStarter = useProjectStarter().projectStarter
96​
97 const availableAddOns = useMemo(() => {
98 if (!ready) return []
99 const baseAddOns = addOnsByMode?.[routerMode] || []
100 return [
101 ...baseAddOns,
102 ...customAddOns.filter((addOn) => addOn.modes.includes(routerMode)),
103 ]
104 }, [ready, routerMode, addOnsByMode, customAddOns])
105​
106 const addOnState = useMemo(() => {
107 if (!ready) return {}
108 const originalAddOns: Set<string> = new Set()
109 for (const addOn of projectStarter?.dependsOn || []) {
110 originalAddOns.add(addOn)
111 }
112 for (const addOn of originalSelectedAddOns) {
113 originalAddOns.add(addOn)
114 }
115 for (const addOn of forcedAddOns || []) {
116 originalAddOns.add(addOn)
117 }
118 return getAddOnStatus(
119 availableAddOns,
120 userSelectedAddOns,
121 Array.from(originalAddOns),
122 )
123 }, [
124 ready,
125 availableAddOns,
126 userSelectedAddOns,
127 originalSelectedAddOns,
128 projectStarter?.dependsOn,
129 forcedAddOns,
130 ])
131​
132 const chosenAddOns = useMemo(() => {
133 if (!ready) return []
134 const addOns = new Set(
135 Object.keys(addOnState).filter((addOn) => addOnState[addOn].selected),
136 )
137 for (const addOn of forcedAddOns || []) {
138 addOns.add(addOn)
139 }
140 return Array.from(addOns)
141 }, [ready, addOnState, forcedAddOns])
142​
143 const toggleAddOn = useCallback(
144 (addOnId: string) => {
145 if (!ready) return
146​
147 if (addOnState[addOnId].isSingleSelect) {
148 if (!addOnState[addOnId].selected) {
149 // Find the currently selected addOn with the same isSingleSelect value and unselect it
150 const singleSelectType = addOnState[addOnId].isSingleSelect
151 const currentlySelected = Object.keys(addOnState).find(
152 (id) =>
153 id !== addOnId &&
154 addOnState[id].isSingleSelect === singleSelectType &&
155 addOnState[id].selected,
156 )
157 useMutableAddOns.setState((state) => {
158 let newUserSelectedAddOns = state.userSelectedAddOns.filter(
159 (id) => id !== currentlySelected, // remove the previously selected one
160 )
161 if (!newUserSelectedAddOns.includes(addOnId)) {
162 newUserSelectedAddOns = [...newUserSelectedAddOns, addOnId]
163 }
164 return {
165 userSelectedAddOns: newUserSelectedAddOns,
166 }
167 })
168 }
169 } else {
170 if (addOnState[addOnId].enabled) {
171 if (addOnState[addOnId].selected) {
172 useMutableAddOns.setState((state) => ({
173 userSelectedAddOns: state.userSelectedAddOns.filter(
174 (addOn) => addOn !== addOnId,
175 ),
176 }))
177 } else {
178 useMutableAddOns.setState((state) => ({
179 userSelectedAddOns: [...state.userSelectedAddOns, addOnId],
180 }))
181 }
182 }
183 }
184 },
185 [ready, addOnState, availableAddOns],
186 )
187​
188 const setAddOnOption = useCallback(
189 (addOnId: string, optionName: string, value: any) => {
190 if (!ready) return
191 useProjectOptions.setState((state) => ({
192 addOnOptions: {
193 ...state.addOnOptions,
194 [addOnId]: {
195 ...state.addOnOptions[addOnId],
196 [optionName]: value,
197 },
198 },
199 }))
200 },
201 [ready],
202 )
203​
204 const getAddOnOptions = useCallback((addOnId: string) => {
205 return useProjectOptions.getState().addOnOptions[addOnId] || {}
206 }, [])
207​
208 return {
209 toggleAddOn,
210 setAddOnOption,
211 getAddOnOptions,
212 chosenAddOns,
213 availableAddOns,
214 userSelectedAddOns,
215 originalSelectedAddOns,
216 addOnState,
217 }
219​
220const useHasProjectStarter = () =>
221 useProjectStarter((state) => state.projectStarter === undefined)
222​
223export const useModeEditable = () => {
224 const ready = useReady()
225 const forcedRouterMode = useForcedRouterMode()
226 const hasProjectStarter = useHasProjectStarter()
227 return ready ? !forcedRouterMode && hasProjectStarter : false
229​
230export const useTypeScriptEditable = () => {
231 // TypeScript is always enabled with TanStack Start
232 return false
234​
235export const useProjectName = () =>
236 useProjectOptions((state) => state.projectName)
237​
238export const useRouterMode = () => {
239 const ready = useReady()
240 const forcedRouterMode = useForcedRouterMode()
241 const userMode = useProjectOptions((state) => state.mode)
242 return ready ? forcedRouterMode || userMode : 'file-router'
244​
245export function useFilters() {
246 const ready = useReady()
247 const includedFiles = useApplicationSettings((state) => state.includeFiles)
248​
249 const toggleFilter = useCallback(
250 (filter: string) => {
251 if (!ready) return
252 useApplicationSettings.setState((state) => ({
253 includeFiles: state.includeFiles.includes(filter)
254 ? state.includeFiles.filter((f) => f !== filter)
255 : [...state.includeFiles, filter],
256 }))
257 },
258 [ready],
259 )
260​
261 return {
262 includedFiles,
263 toggleFilter,
264 }
266​
267export function useDryRun() {
268 const ready = useReady()
269 const applicationMode = useApplicationMode()
270 const { initialized, ...projectOptions } = useProjectOptions()
271 const { userSelectedAddOns, chosenAddOns } = useAddOns()
272 const projectStarter = useProjectStarter().projectStarter
273​
274 const { data: dryRunOutput } = useQuery<DryRunOutput>({
275 queryKey: [
276 'dry-run',
277 applicationMode,
278 JSON.stringify(projectOptions),
279 JSON.stringify(userSelectedAddOns),
280 projectStarter?.url,
281 ],
282 queryFn: async () => {
283 if (applicationMode === 'none' || !ready || !initialized) {
284 return {
285 files: {},
286 commands: [],
287 deletedFiles: [],
288 }
289 } else if (applicationMode === 'setup') {
290 return dryRunCreateApp(projectOptions, chosenAddOns, projectStarter)
291 } else {
292 return dryRunAddToApp(userSelectedAddOns)
293 }
294 },
295 enabled: ready,
296 initialData: {
297 files: {},
298 commands: [],
299 deletedFiles: [],
300 },
301 })
302​
303 return dryRunOutput
305​
306type StartupDialogState = {
307 open: boolean
308 dontShowAgain: boolean
309 setOpen: (open: boolean) => void
310 setDontShowAgain: (dontShowAgain: boolean) => void
312​
313export const useStartupDialog = create<StartupDialogState>()(
314 persist(
315 (set) => ({
316 open: false,
317 dontShowAgain: false,
318 setOpen: (open) => set({ open }),
319 setDontShowAgain: (dontShowAgain) => set({ dontShowAgain }),
320 }),
321 {
322 name: 'startup-dialog',
323 partialize: (state) => ({
324 dontShowAgain: state.dontShowAgain,
325 }),
326 merge: (persistedState: unknown, currentState) => {
327 if (
328 persistedState &&
329 (persistedState as { dontShowAgain?: boolean }).dontShowAgain
330 ) {
331 currentState.open = false
332 } else {
333 currentState.open = true
334 }
335 return currentState
336 },
337 },
338 ),
340​
341export const setProjectName = (projectName: string) =>
342 useProjectOptions.setState({
343 projectName,
344 })
345​
346export const setRouterMode = (mode: string) =>
347 useProjectOptions.setState({
348 mode,
349 })
350​
351export function setTypeScript(typescript: boolean) {
352 useProjectOptions.setState({
353 typescript,
354 })
356​
357export function setProjectStarter(starter: StarterInfo | undefined) {
358 useProjectStarter.setState(() => ({
359 projectStarter: starter,
360 }))
361 if (starter) {
362 useProjectOptions.setState({
363 mode: starter.mode,
364 })
365 }
367​
368export function useManager() {
369 const ready = useReady()
370 const originalOptions = useOriginalOptions()
371​
372 useEffect(() => {
373 if (ready) {
374 useProjectOptions.setState({
375 ...originalOptions,
376 initialized: true,
377 })
378 }
379 }, [ready])