File size: 7,395 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import * as p from "@clack/prompts"
import { boxen } from "@visulima/boxen"
import { Command } from "commander"
import createDebug from "debug"
import { existsSync } from "fs"
import { writeFile } from "fs/promises"
import { join } from "node:path/posix"
import { getProjectContext } from "../utils/context"
import { convertTsxToJsx } from "../utils/convert-tsx-to-jsx"
import { fetchComposition, fetchCompositions } from "../utils/fetch"
import {
  findCompositionById,
  getFileDependencies,
} from "../utils/get-file-dependencies"
import { ensureDir } from "../utils/io"
import { installCommand } from "../utils/run-command"
import {
  type CompositionFile,
  type Compositions,
  addCommandFlagsSchema,
} from "../utils/schema"
import { uniq } from "../utils/shared"
import { tasks } from "../utils/tasks"

const debug = createDebug("chakra:snippet")

export const SnippetCommand = new Command("snippet")
  .description("Add snippets to your project for better DX")
  .addCommand(
    new Command("add")
      .description("Add a new snippet for better DX")
      .argument("[snippets...]", "snippets to add")
      .option("-d, --dry-run", "Dry run")
      .option("--outdir <dir>", "Output directory to write the snippets")
      .option("--all", "Add all snippets")
      .option("-f, --force", "Overwrite existing files")
      .option("--tsx", "Convert to TSX")
      .action(async (selectedComponents: string[], flags: unknown) => {
        const parsedFlags = addCommandFlagsSchema.parse(flags)
        const { dryRun, force, all, tsx } = parsedFlags

        const ctx = await getProjectContext({
          cwd: parsedFlags.outdir || process.cwd(),
          tsx,
        })

        debug("context", ctx)

        const jsx = !ctx.isTypeScript

        const outdir = parsedFlags.outdir || ctx.scope.componentsDir
        ensureDir(outdir)

        const items = await fetchCompositions()

        const inferredComponents = getComponents({
          components: selectedComponents,
          all,
          items,
        })

        const components = inferredComponents.items
        debug("components", components)

        p.log.info(inferredComponents.message)

        const deps = uniq(
          components.flatMap((id) => getFileDependencies(items, id)),
        )

        const fileDependencies = uniq(
          deps.map((dep) => dep.fileDependencies).flat(),
        )
        const npmDependencies = uniq(
          deps.map((dep) => dep.npmDependencies).flat(),
        )

        debug("fileDependencies", fileDependencies)
        debug("npmDependencies", npmDependencies)

        let skippedFiles: string[] = []

        await tasks([
          {
            title: `Installing required dependencies...`,
            enabled: !!npmDependencies.length && !dryRun,
            task: () =>
              installCommand([...npmDependencies, "--silent"], outdir),
          },
          {
            title: "Writing file dependencies",
            enabled: !!fileDependencies.length && !dryRun,
            task: async () => {
              await Promise.all(
                fileDependencies.map(async (dep) => {
                  if (existsSync(join(outdir, dep)) && !force) {
                    skippedFiles.push(dep)
                    return
                  }
                  const item = await fetchComposition(dep)

                  if (jsx) {
                    item.file.name = item.file.name.replace(".tsx", ".jsx")
                    await transformToJsx(item)
                  }

                  const outPath = join(outdir, item.file.name)

                  await writeFile(
                    outPath,
                    item.file.content.replace("compositions/ui", "."),
                    "utf-8",
                  )
                }),
              )
            },
          },
          {
            title: "Writing selected snippets",
            task: async () => {
              await Promise.all(
                components.map(async (id) => {
                  let filename =
                    findCompositionById(items, id)?.file ?? id + ".tsx"
                  if (jsx) {
                    filename = filename.replace(".tsx", ".jsx")
                  }

                  if (existsSync(join(outdir, filename)) && !force) {
                    skippedFiles.push(id)
                    return
                  }

                  try {
                    const item = await fetchComposition(id)
                    if (jsx) {
                      item.file.name = item.file.name.replace(".tsx", ".jsx")
                      await transformToJsx(item)
                    }

                    const outPath = join(outdir, item.file.name)

                    if (dryRun) {
                      printFileSync(item)
                    } else {
                      await writeFile(
                        outPath,
                        item.file.content.replace("compositions/ui", "."),
                        "utf-8",
                      )
                    }
                  } catch (error) {
                    if (error instanceof Error) {
                      p.log.error(error?.message)
                      process.exit(0)
                    }
                  }
                }),
              )
            },
          },
        ])

        if (skippedFiles.length) {
          p.log.warn(
            `Skipping ${skippedFiles.length} file(s) that already exist. Use the --force flag to overwrite.`,
          )
        }

        p.outro("๐ŸŽ‰ Done!")
      }),
  )

  .addCommand(
    new Command("list")
      .description("List available snippets")
      .action(async () => {
        const { default: Table } = await import("cli-table")

        const table = new Table({
          head: ["name", "dependencies"],
          colWidths: [20, 30],
          style: { compact: true },
        })

        const items = await fetchCompositions()

        if (!Array.isArray(items)) {
          throw new Error("[chakra] invalid json response")
        }

        items.forEach((item) => {
          const deps = item.npmDependencies
          const depsString = deps.length ? deps.join(", ") : "-"
          table.push([item.id, depsString])
        })

        p.log.info(`Found ${items.length} snippets`)

        p.log.info(table.toString())

        p.outro("๐ŸŽ‰ Done!")
      }),
  )

async function transformToJsx(item: CompositionFile) {
  const content = await convertTsxToJsx(item.file.content)
  item.file.content = content
  item.file.name = item.file.name.replace(".tsx", ".jsx")
}

function printFileSync(item: CompositionFile) {
  const boxText = boxen(item.file.content, {
    headerText: `${item.file.name}\n`,
    borderStyle: "none",
  })
  p.log.info(boxText)
}

const RECOMMENDED_SNIPPETS = ["provider", "toaster", "tooltip"]

function getComponents(opts: {
  components: string[]
  all: boolean | undefined
  items: Compositions
}) {
  const { components, all, items } = opts
  if (components.length === 0 && !all)
    return {
      message: "No component(s) selected, adding recommended snippets...",
      items: RECOMMENDED_SNIPPETS,
    }

  if (all)
    return {
      message: "Adding all snippets...",
      items: items.map((item) => item.id),
    }

  return {
    message: `Adding ${components.length} snippet(s)...`,
    items: components,
  }
}