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

project.ts

395 lines10.8 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/cta-engine'
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 const ready = useReady()
232 const hasProjectStarter = useHasProjectStarter()
233 const routerMode = useRouterMode()
234 return ready ? hasProjectStarter && routerMode === 'code-router' : false
236​
237export const useTailwindEditable = () => {
238 const ready = useReady()
239 const hasProjectStarter = useHasProjectStarter()
240 const routerMode = useRouterMode()
241 return ready ? hasProjectStarter && routerMode === 'code-router' : false
243​
244export const useProjectName = () =>
245 useProjectOptions((state) => state.projectName)
246​
247export const useRouterMode = () => {
248 const ready = useReady()
249 const forcedRouterMode = useForcedRouterMode()
250 const userMode = useProjectOptions((state) => state.mode)
251 return ready ? forcedRouterMode || userMode : 'file-router'
253​
254export function useFilters() {
255 const ready = useReady()
256 const includedFiles = useApplicationSettings((state) => state.includeFiles)
257​
258 const toggleFilter = useCallback(
259 (filter: string) => {
260 if (!ready) return
261 useApplicationSettings.setState((state) => ({
262 includeFiles: state.includeFiles.includes(filter)
263 ? state.includeFiles.filter((f) => f !== filter)
264 : [...state.includeFiles, filter],
265 }))
266 },
267 [ready],
268 )
269​
270 return {
271 includedFiles,
272 toggleFilter,
273 }
275​
276export function useDryRun() {
277 const ready = useReady()
278 const applicationMode = useApplicationMode()
279 const { initialized, ...projectOptions } = useProjectOptions()
280 const { userSelectedAddOns, chosenAddOns } = useAddOns()
281 const projectStarter = useProjectStarter().projectStarter
282​
283 const { data: dryRunOutput } = useQuery<DryRunOutput>({
284 queryKey: [
285 'dry-run',
286 applicationMode,
287 JSON.stringify(projectOptions),
288 JSON.stringify(userSelectedAddOns),
289 projectStarter?.url,
290 ],
291 queryFn: async () => {
292 if (applicationMode === 'none' || !ready || !initialized) {
293 return {
294 files: {},
295 commands: [],
296 deletedFiles: [],
297 }
298 } else if (applicationMode === 'setup') {
299 return dryRunCreateApp(projectOptions, chosenAddOns, projectStarter)
300 } else {
301 return dryRunAddToApp(userSelectedAddOns)
302 }
303 },
304 enabled: ready,
305 initialData: {
306 files: {},
307 commands: [],
308 deletedFiles: [],
309 },
310 })
311​
312 return dryRunOutput
314​
315type StartupDialogState = {
316 open: boolean
317 dontShowAgain: boolean
318 setOpen: (open: boolean) => void
319 setDontShowAgain: (dontShowAgain: boolean) => void
321​
322export const useStartupDialog = create<StartupDialogState>()(
323 persist(
324 (set) => ({
325 open: false,
326 dontShowAgain: false,
327 setOpen: (open) => set({ open }),
328 setDontShowAgain: (dontShowAgain) => set({ dontShowAgain }),
329 }),
330 {
331 name: 'startup-dialog',
332 partialize: (state) => ({
333 dontShowAgain: state.dontShowAgain,
334 }),
335 merge: (persistedState: unknown, currentState) => {
336 if (
337 persistedState &&
338 (persistedState as { dontShowAgain?: boolean }).dontShowAgain
339 ) {
340 currentState.open = false
341 } else {
342 currentState.open = true
343 }
344 return currentState
345 },
346 },
347 ),
349​
350export const setProjectName = (projectName: string) =>
351 useProjectOptions.setState({
352 projectName,
353 })
354​
355export const setRouterMode = (mode: string) =>
356 useProjectOptions.setState({
357 mode,
358 })
359​
360export function setTypeScript(typescript: boolean) {
361 useProjectOptions.setState({
362 typescript,
363 })
365​
366export function setTailwind(tailwind: boolean) {
367 useProjectOptions.setState({
368 tailwind,
369 })
371​
372export function setProjectStarter(starter: StarterInfo | undefined) {
373 useProjectStarter.setState(() => ({
374 projectStarter: starter,
375 }))
376 if (starter) {
377 useProjectOptions.setState({
378 mode: starter.mode,
379 })
380 }
382​
383export function useManager() {
384 const ready = useReady()
385 const originalOptions = useOriginalOptions()
386​
387 useEffect(() => {
388 if (ready) {
389 useProjectOptions.setState({
390 ...originalOptions,
391 initialized: true,
392 })
393 }
394 }, [ready])