Skip to content

Commit

Permalink
feat(cli): add non-studio app template
Browse files Browse the repository at this point in the history
  • Loading branch information
cngonzalez committed Jan 23, 2025
1 parent 4f50336 commit 42d8ae5
Show file tree
Hide file tree
Showing 11 changed files with 127 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,22 @@ export interface BootstrapLocalOptions {
variables: GenerateConfigOptions['variables']
}

/*
* Certain apps will not be studios, and shouldn't receive
* some of the studio-specific setup.
*/
const nonStudioTemplates = ['core-app']

export async function bootstrapLocalTemplate(
opts: BootstrapLocalOptions,
context: CliCommandContext,
): Promise<ProjectTemplate> {
const {apiClient, cliRoot, output} = context
const templatesDir = path.join(cliRoot, 'templates')
const {outputPath, templateName, useTypeScript, packageName, variables} = opts
const {projectId} = variables
const sourceDir = path.join(templatesDir, templateName)
const sharedDir = path.join(templatesDir, 'shared')
const isStudioTemplate = !nonStudioTemplates.includes(templateName)

// Check that we have a template info file (dependencies, plugins etc)
const template = templates[templateName]
Expand Down Expand Up @@ -81,15 +87,16 @@ export async function bootstrapLocalTemplate(
// Resolve latest versions of Sanity-dependencies
spinner = output.spinner('Resolving latest module versions').start()
const dependencyVersions = await resolveLatestVersions({
...studioDependencies.dependencies,
...(isStudioTemplate ? studioDependencies.dependencies : {}),
...studioDependencies.devDependencies,
...(template.dependencies || {}),
...(template.devDependencies || {}),
})
spinner.succeed()

// Use the resolved version for the given dependency
const dependencies = Object.keys({
...studioDependencies.dependencies,
...(isStudioTemplate ? studioDependencies.dependencies : {}),
...template.dependencies,
}).reduce(
(deps, dependency) => {
Expand All @@ -116,6 +123,7 @@ export async function bootstrapLocalTemplate(
name: packageName,
dependencies,
devDependencies,
scripts: template.scripts,
})

// ...and a studio config (`sanity.config.[ts|js]`)
Expand All @@ -133,15 +141,21 @@ export async function bootstrapLocalTemplate(

// Write non-template files to disc
const codeExt = useTypeScript ? 'ts' : 'js'
await Promise.all([
writeFileIfNotExists(`sanity.config.${codeExt}`, studioConfig),
writeFileIfNotExists(`sanity.cli.${codeExt}`, cliConfig),
writeFileIfNotExists('package.json', packageManifest),
writeFileIfNotExists(
'eslint.config.mjs',
`import studio from '@sanity/eslint-config-studio'\n\nexport default [...studio]\n`,
),
])
await Promise.all(
[
...[
isStudioTemplate
? writeFileIfNotExists(`sanity.config.${codeExt}`, studioConfig)
: Promise.resolve(null),
],
writeFileIfNotExists(`sanity.cli.${codeExt}`, cliConfig),
writeFileIfNotExists('package.json', packageManifest),
writeFileIfNotExists(
'eslint.config.mjs',
`import studio from '@sanity/eslint-config-studio'\n\nexport default [...studio]\n`,
),
].filter(Boolean),
)

debug('Updating initial template metadata')
await updateInitialTemplateMetadata(apiClient, variables.projectId, `cli-${templateName}`)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ export function createPackageManifest(

main: 'package.json',
keywords: ['sanity'],
scripts: {
// default to studio scripts, but allow templates to provide their own
scripts: data.scripts || {
'dev': 'sanity dev',
'start': 'sanity start',
'build': 'sanity build',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ export interface ProjectTemplate {
datasetUrl?: string
dependencies?: Record<string, string>
devDependencies?: Record<string, string>
scripts?: Record<string, string>
importPrompt?: string
configTemplate?: string | ((variables: GenerateConfigOptions['variables']) => string)
typescriptOnly?: boolean
Expand Down
20 changes: 20 additions & 0 deletions packages/@sanity/cli/src/actions/init-project/templates/coreApp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {type ProjectTemplate} from '../initProject'

const coreAppTemplate: ProjectTemplate = {
scripts: {
dev: 'vite',
build: 'vite build',
preview: 'vite preview',
},
dependencies: {
'react': '^19',
'react-dom': '^19',
'@sanity/sdk': '^0.0.0-alpha',
'@sanity/sdk-react': '^0.0.0-alpha',
},
devDependencies: {
vite: '^6',
},
}

export default coreAppTemplate
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {type ProjectTemplate} from '../initProject'
import blog from './blog'
import clean from './clean'
import coreAppTemplate from './coreApp'
import getStartedTemplate from './getStarted'
import moviedb from './moviedb'
import quickstart from './quickstart'
Expand All @@ -10,6 +11,7 @@ import shopifyOnline from './shopifyOnline'
const templates: Record<string, ProjectTemplate | undefined> = {
blog,
clean,
'core-app': coreAppTemplate,
'get-started': getStartedTemplate,
moviedb,
shopify,
Expand Down
1 change: 1 addition & 0 deletions packages/@sanity/cli/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export interface PackageJson {
peerDependencies?: Record<string, string>

repository?: {type: string; url: string}
scripts?: Record<string, string>
}

export interface CliCommandGroupDefinition {
Expand Down
13 changes: 13 additions & 0 deletions packages/@sanity/cli/templates/core-app/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
46 changes: 46 additions & 0 deletions packages/@sanity/cli/templates/core-app/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import {createSanityInstance} from '@sanity/sdk'
import {SanityProvider} from '@sanity/sdk-react/context'
import {useCurrentUser, useLogOut} from '@sanity/sdk-react/hooks'
import {Button, Flex, Spinner, Text, ThemeProvider} from '@sanity/ui'
import {buildTheme} from '@sanity/ui/theme'
import {Suspense} from 'react'

const theme = buildTheme({})
const sanityInstance = createSanityInstance({
projectId: '<your-project-id>',
dataset: '<your-dataset>',
// optional auth config set projectId and dataset to '' and authScope to 'org' for a global token
// auth: {
// authScope: 'org',
// ...
// },
})

export function App() {
return (
<ThemeProvider theme={theme}>
<Suspense fallback={<Spinner />}>
<SanityProvider sanityInstance={sanityInstance}>
{/* You will need to implement an auth boundary */}
<AuthBoundary header={<Text>My Sanity App</Text>}>
<Authenticated />
</AuthBoundary>
</SanityProvider>
</Suspense>
</ThemeProvider>
)
}

function Authenticated() {
const currentUser = useCurrentUser()
const logout = useLogOut()

return (
<Flex direction="column" gap={2}>
<Text>Hello, {currentUser?.name}!</Text>
<Button text="Logout" onClick={logout} mode="ghost" />
</Flex>
)
}

export default App
9 changes: 9 additions & 0 deletions packages/@sanity/cli/templates/core-app/src/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'

createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
7 changes: 7 additions & 0 deletions packages/@sanity/cli/templates/core-app/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})
1 change: 0 additions & 1 deletion packages/sanity/src/presentation/loader/LoaderQueries.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,6 @@ export function turboChargeResultIfSourceMap<T = unknown>(
return applySourceDocuments(
result,
resultSourceMap,
// @ts-expect-error - @TODO fix later
(sourceDocument) => {
if (sourceDocument._projectId) {
// @TODO Handle cross dataset references
Expand Down

0 comments on commit 42d8ae5

Please sign in to comment.