@canonical/summon-component 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Template context creation for component generators
3
+ */
4
+
5
+ import { getComponentName, kebabCase } from "./string-helpers.js";
6
+ import type {
7
+ BaseComponentAnswers,
8
+ Framework,
9
+ TemplateContext,
10
+ } from "./types.js";
11
+
12
+ /**
13
+ * Create template context from answers
14
+ */
15
+ export const createTemplateContext = (
16
+ answers: BaseComponentAnswers,
17
+ framework: Framework,
18
+ ): TemplateContext => {
19
+ const name = getComponentName(answers.componentPath);
20
+ return {
21
+ name,
22
+ kebabName: kebabCase(name),
23
+ generatorName: `@canonical/summon:component-${framework}`,
24
+ version: "0.1.0",
25
+ withStyles: answers.withStyles,
26
+ withStories: answers.withStories,
27
+ withSsrTests: answers.withSsrTests,
28
+ };
29
+ };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Shared types for component generators
3
+ */
4
+
5
+ export type Framework = "react" | "svelte";
6
+
7
+ /** Base answers shared across component generators */
8
+ export interface BaseComponentAnswers {
9
+ /** Full path to the component directory (e.g., src/components/Button) */
10
+ componentPath: string;
11
+ /** Include CSS styles */
12
+ withStyles: boolean;
13
+ /** Include Storybook stories */
14
+ withStories: boolean;
15
+ /** Include SSR tests */
16
+ withSsrTests: boolean;
17
+ }
18
+
19
+ export interface TemplateContext {
20
+ /** Component name in PascalCase (e.g., MyComponent) */
21
+ name: string;
22
+ /** Component name in kebab-case (e.g., my-component) */
23
+ kebabName: string;
24
+ /** Generator name for comments */
25
+ generatorName: string;
26
+ /** Generator version */
27
+ version: string;
28
+ /** Include styles */
29
+ withStyles: boolean;
30
+ /** Include stories */
31
+ withStories: boolean;
32
+ /** Include SSR tests */
33
+ withSsrTests: boolean;
34
+ /** Index signature for compatibility with Record<string, unknown> */
35
+ [key: string]: unknown;
36
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Validation utilities for component generators
3
+ */
4
+
5
+ import * as path from "node:path";
6
+
7
+ /**
8
+ * Check if a string is in PascalCase
9
+ */
10
+ export const isPascalCase = (str: string): boolean => {
11
+ return /^[A-Z][a-zA-Z0-9]*$/.test(str);
12
+ };
13
+
14
+ /**
15
+ * Validate component path
16
+ */
17
+ export const validateComponentPath = (value: unknown): true | string => {
18
+ if (!value || typeof value !== "string") {
19
+ return "Component path is required";
20
+ }
21
+ const name = path.basename(value);
22
+ if (!isPascalCase(name)) {
23
+ return "Component name must be in PascalCase (e.g., MyComponent)";
24
+ }
25
+ return true;
26
+ };
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Svelte Component Generator
3
+ *
4
+ * Generates a Svelte 5 component with a consistent file structure:
5
+ * - `ComponentName.svelte` - Main component file with Svelte 5 runes ($props)
6
+ * - `types.ts` - TypeScript types and props interface
7
+ * - `index.ts` - Barrel export
8
+ * - `ComponentName.svelte.test.ts` - Unit tests with @testing-library/svelte
9
+ * - `ComponentName.ssr.test.ts` - SSR tests (optional)
10
+ * - `ComponentName.stories.svelte` - Svelte CSF stories (optional)
11
+ * - `ComponentName.stories.ts` - TypeScript stories (optional, alternative to Svelte CSF)
12
+ *
13
+ * @example
14
+ * ```bash
15
+ * summon component svelte --component-path=src/lib/components/Button
16
+ * summon component svelte --component-path=src/lib/components/Card --with-stories
17
+ * summon component svelte --component-path=src/lib/components/Modal --with-stories --use-ts-stories
18
+ * ```
19
+ *
20
+ * @module
21
+ */
22
+
23
+ import * as path from "node:path";
24
+ import { fileURLToPath } from "node:url";
25
+ import {
26
+ debug,
27
+ type GeneratorDefinition,
28
+ info,
29
+ mkdir,
30
+ sequence_,
31
+ template,
32
+ when,
33
+ } from "@canonical/summon";
34
+
35
+ import {
36
+ appendExportToParentIndex,
37
+ createComponentPathPrompt,
38
+ createTemplateContext,
39
+ getComponentName,
40
+ getParentDir,
41
+ sharedPrompts,
42
+ } from "../shared/index.js";
43
+ import type { SvelteComponentAnswers } from "./types.js";
44
+
45
+ // =============================================================================
46
+ // Template Paths
47
+ // =============================================================================
48
+
49
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
50
+ const templatesDir = path.join(__dirname, "..", "templates");
51
+
52
+ const svelteTemplates = {
53
+ component: path.join(templatesDir, "svelte", "component.svelte.ejs"),
54
+ types: path.join(templatesDir, "svelte", "types.ts.ejs"),
55
+ index: path.join(templatesDir, "svelte", "index.ts.ejs"),
56
+ test: path.join(templatesDir, "svelte", "test.ts.ejs"),
57
+ ssrTest: path.join(templatesDir, "svelte", "ssr.test.ts.ejs"),
58
+ storiesSvelte: path.join(templatesDir, "svelte", "stories.svelte.ejs"),
59
+ storiesTs: path.join(templatesDir, "svelte", "stories.ts.ejs"),
60
+ };
61
+
62
+ // =============================================================================
63
+ // Generator Definition
64
+ // =============================================================================
65
+
66
+ /**
67
+ * Svelte component generator definition.
68
+ *
69
+ * This generator creates a complete Svelte 5 component with TypeScript support,
70
+ * runes ($props), testing infrastructure, and optional Storybook stories.
71
+ *
72
+ * @see {@link https://summon.dev/generators/component/svelte} for documentation
73
+ */
74
+ export const generator = {
75
+ meta: {
76
+ name: "component/svelte",
77
+ description:
78
+ "Generate a Svelte 5 component with TypeScript, tests, and stories",
79
+ version: "0.1.0",
80
+ help: `Generate a Svelte 5 component with TypeScript, tests, and stories.
81
+
82
+ FEATURES:
83
+ - Svelte 5 with runes ($props)
84
+ - TypeScript types and props interface
85
+ - Unit tests with @testing-library/svelte
86
+ - Storybook integration (Svelte CSF or TypeScript)
87
+ - Optional scoped styles
88
+ - SSR tests (optional)
89
+ - Auto-export from parent index.ts
90
+
91
+ The component name is extracted from the path and must be PascalCase.
92
+ For example, 'src/lib/components/Button' creates a 'Button' component.`,
93
+ examples: [
94
+ "summon component svelte --component-path=src/lib/components/Button",
95
+ "summon component svelte --component-path=src/lib/components/Card --with-styles --with-stories",
96
+ "summon component svelte --component-path=src/lib/components/Modal --with-stories --use-ts-stories",
97
+ "summon component svelte --component-path=src/lib/components/Button --dry-run",
98
+ ],
99
+ },
100
+
101
+ prompts: [
102
+ createComponentPathPrompt("svelte"),
103
+ ...sharedPrompts,
104
+ {
105
+ name: "useTsStories",
106
+ type: "confirm",
107
+ message: "Use TypeScript stories format? (otherwise Svelte CSF)",
108
+ default: false,
109
+ when: (answers) => answers.withStories === true,
110
+ group: "Options",
111
+ },
112
+ ],
113
+
114
+ generate: (answers) => {
115
+ const componentName = getComponentName(answers.componentPath);
116
+ const componentDir = answers.componentPath;
117
+ const parentDir = getParentDir(answers.componentPath);
118
+ const ctx = createTemplateContext(answers, "svelte");
119
+
120
+ return sequence_([
121
+ info(`Generating Svelte component: ${componentName}`),
122
+
123
+ debug("Creating component directory"),
124
+ mkdir(componentDir),
125
+
126
+ debug("Creating main component file"),
127
+ template({
128
+ source: svelteTemplates.component,
129
+ dest: path.join(componentDir, `${componentName}.svelte`),
130
+ vars: ctx,
131
+ }),
132
+
133
+ debug("Creating types file"),
134
+ template({
135
+ source: svelteTemplates.types,
136
+ dest: path.join(componentDir, "types.ts"),
137
+ vars: ctx,
138
+ }),
139
+
140
+ debug("Creating index barrel file"),
141
+ template({
142
+ source: svelteTemplates.index,
143
+ dest: path.join(componentDir, "index.ts"),
144
+ vars: ctx,
145
+ }),
146
+
147
+ debug("Creating test file"),
148
+ template({
149
+ source: svelteTemplates.test,
150
+ dest: path.join(componentDir, `${componentName}.svelte.test.ts`),
151
+ vars: ctx,
152
+ }),
153
+
154
+ when(answers.withSsrTests, debug("Creating SSR test file")),
155
+ when(
156
+ answers.withSsrTests,
157
+ template({
158
+ source: svelteTemplates.ssrTest,
159
+ dest: path.join(componentDir, `${componentName}.ssr.test.ts`),
160
+ vars: ctx,
161
+ }),
162
+ ),
163
+
164
+ when(
165
+ answers.withStories && !answers.useTsStories,
166
+ debug("Creating Svelte CSF stories file"),
167
+ ),
168
+ when(
169
+ answers.withStories && !answers.useTsStories,
170
+ template({
171
+ source: svelteTemplates.storiesSvelte,
172
+ dest: path.join(componentDir, `${componentName}.stories.svelte`),
173
+ vars: ctx,
174
+ }),
175
+ ),
176
+
177
+ when(
178
+ answers.withStories && answers.useTsStories,
179
+ debug("Creating TypeScript stories file"),
180
+ ),
181
+ when(
182
+ answers.withStories && answers.useTsStories,
183
+ template({
184
+ source: svelteTemplates.storiesTs,
185
+ dest: path.join(componentDir, `${componentName}.stories.ts`),
186
+ vars: ctx,
187
+ }),
188
+ ),
189
+
190
+ debug("Updating parent index.ts with export"),
191
+ appendExportToParentIndex(parentDir, componentName),
192
+
193
+ info(`Created ${componentName} component at ${componentDir}`),
194
+ ]);
195
+ },
196
+ } as const satisfies GeneratorDefinition<SvelteComponentAnswers>;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Svelte Component Generator - Barrel export
3
+ */
4
+
5
+ export { generator } from "./generator.js";
6
+ export type { SvelteComponentAnswers } from "./types.js";
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Types for Svelte component generator
3
+ */
4
+
5
+ import type { BaseComponentAnswers } from "../shared/index.js";
6
+
7
+ /** Svelte component generator answers */
8
+ export interface SvelteComponentAnswers extends BaseComponentAnswers {
9
+ /** Use TypeScript stories format instead of Svelte CSF */
10
+ useTsStories: boolean;
11
+ }
@@ -0,0 +1,24 @@
1
+ // Generated by <%= generatorName %> v<%= version %>
2
+
3
+ import type { <%= name %>Props } from "./types";
4
+ <% if (withStyles) { -%>
5
+ import "./styles.css";
6
+ <% } -%>
7
+
8
+ /**
9
+ * <%= name %> component
10
+ */
11
+ export const <%= name %> = ({
12
+ className,
13
+ children,
14
+ ...props
15
+ }: <%= name %>Props): JSX.Element => {
16
+ return (
17
+ <div
18
+ className={`<%= kebabName %>${className ? ` ${className}` : ""}`}
19
+ {...props}
20
+ >
21
+ {children}
22
+ </div>
23
+ );
24
+ };
@@ -0,0 +1,4 @@
1
+ // Generated by <%= generatorName %> v<%= version %>
2
+
3
+ export { <%= name %> } from "./<%= name %>";
4
+ export type { <%= name %>Props } from "./types";
@@ -0,0 +1,13 @@
1
+ // Generated by <%= generatorName %> v<%= version %>
2
+
3
+ import { describe, expect, it } from "vitest";
4
+ import { renderToString } from "react-dom/server";
5
+ import { <%= name %> } from "./<%= name %>";
6
+
7
+ describe("<%= name %> SSR", () => {
8
+ it("renders without hydration errors", () => {
9
+ const html = renderToString(<<%= name %>>Test content</<%= name %>>);
10
+ expect(html).toContain("Test content");
11
+ expect(html).toContain("<%= kebabName %>");
12
+ });
13
+ });
@@ -0,0 +1,26 @@
1
+ // Generated by <%= generatorName %> v<%= version %>
2
+
3
+ import type { Meta, StoryObj } from "@storybook/react";
4
+ import { <%= name %> } from "./<%= name %>";
5
+
6
+ const meta: Meta<typeof <%= name %>> = {
7
+ title: "Components/<%= name %>",
8
+ component: <%= name %>,
9
+ tags: ["autodocs"],
10
+ };
11
+
12
+ export default meta;
13
+ type Story = StoryObj<typeof <%= name %>>;
14
+
15
+ export const Default: Story = {
16
+ args: {
17
+ children: "Hello, <%= name %>!",
18
+ },
19
+ };
20
+
21
+ export const WithCustomClass: Story = {
22
+ args: {
23
+ children: "Custom styled",
24
+ className: "custom-class",
25
+ },
26
+ };
@@ -0,0 +1,24 @@
1
+ // Generated by <%= generatorName %> v<%= version %>
2
+
3
+ import { describe, expect, it } from "vitest";
4
+ import { render, screen } from "@testing-library/react";
5
+ import { <%= name %> } from "./<%= name %>";
6
+
7
+ describe("<%= name %>", () => {
8
+ it("renders children", () => {
9
+ render(<<%= name %>>Test content</<%= name %>>);
10
+ expect(screen.getByText("Test content")).toBeInTheDocument();
11
+ });
12
+
13
+ it("applies custom className", () => {
14
+ render(<<%= name %> className="custom-class">Content</<%= name %>>);
15
+ const element = screen.getByText("Content");
16
+ expect(element).toHaveClass("<%= kebabName %>");
17
+ expect(element).toHaveClass("custom-class");
18
+ });
19
+
20
+ it("passes through additional props", () => {
21
+ render(<<%= name %> data-testid="test-component">Content</<%= name %>>);
22
+ expect(screen.getByTestId("test-component")).toBeInTheDocument();
23
+ });
24
+ });
@@ -0,0 +1,8 @@
1
+ // Generated by <%= generatorName %> v<%= version %>
2
+
3
+ import type { HTMLAttributes, ReactNode } from "react";
4
+
5
+ export interface <%= name %>Props extends HTMLAttributes<HTMLDivElement> {
6
+ /** Content to render inside the component */
7
+ children?: ReactNode;
8
+ }
@@ -0,0 +1,5 @@
1
+ /* Generated by <%= generatorName %> v<%= version %> */
2
+
3
+ .<%= kebabName %> {
4
+ /* Component styles */
5
+ }
@@ -0,0 +1,25 @@
1
+ <!-- Generated by <%= generatorName %> v<%= version %> -->
2
+
3
+ <script lang="ts">
4
+ import type { <%= name %>Props } from "./types";
5
+
6
+ let {
7
+ class: className = "",
8
+ children,
9
+ ...props
10
+ }: <%= name %>Props = $props();
11
+ </script>
12
+
13
+ <div
14
+ class="<%= kebabName %>{className ? ` ${className}` : ''}"
15
+ {...props}
16
+ >
17
+ {@render children?.()}
18
+ </div>
19
+ <% if (withStyles) { %>
20
+ <style>
21
+ .<%= kebabName %> {
22
+ /* Component styles */
23
+ }
24
+ </style>
25
+ <% } -%>
@@ -0,0 +1,4 @@
1
+ // Generated by <%= generatorName %> v<%= version %>
2
+
3
+ export { default as <%= name %> } from "./<%= name %>.svelte";
4
+ export type { <%= name %>Props } from "./types";
@@ -0,0 +1,12 @@
1
+ // Generated by <%= generatorName %> v<%= version %>
2
+
3
+ import { describe, expect, it } from "vitest";
4
+ import { render } from "svelte/server";
5
+ import <%= name %> from "./<%= name %>.svelte";
6
+
7
+ describe("<%= name %> SSR", () => {
8
+ it("renders on server without errors", () => {
9
+ const { body } = render(<%= name %>);
10
+ expect(body).toContain("<%= kebabName %>");
11
+ });
12
+ });
@@ -0,0 +1,20 @@
1
+ <!-- Generated by <%= generatorName %> v<%= version %> -->
2
+
3
+ <script lang="ts" module>
4
+ import { defineMeta } from "@storybook/addon-svelte-csf";
5
+ import <%= name %> from "./<%= name %>.svelte";
6
+
7
+ const { Story } = defineMeta({
8
+ title: "Components/<%= name %>",
9
+ component: <%= name %>,
10
+ tags: ["autodocs"],
11
+ });
12
+ </script>
13
+
14
+ <Story name="Default">
15
+ <<%= name %>>Hello, <%= name %>!</<%= name %>>
16
+ </Story>
17
+
18
+ <Story name="WithCustomClass">
19
+ <<%= name %> class="custom-class">Custom styled</<%= name %>>
20
+ </Story>
@@ -0,0 +1,21 @@
1
+ // Generated by <%= generatorName %> v<%= version %>
2
+
3
+ import type { Meta, StoryObj } from "@storybook/svelte";
4
+ import <%= name %> from "./<%= name %>.svelte";
5
+
6
+ const meta: Meta<typeof <%= name %>> = {
7
+ title: "Components/<%= name %>",
8
+ component: <%= name %>,
9
+ tags: ["autodocs"],
10
+ };
11
+
12
+ export default meta;
13
+ type Story = StoryObj<typeof <%= name %>>;
14
+
15
+ export const Default: Story = {};
16
+
17
+ export const WithCustomClass: Story = {
18
+ args: {
19
+ class: "custom-class",
20
+ },
21
+ };
@@ -0,0 +1,18 @@
1
+ // Generated by <%= generatorName %> v<%= version %>
2
+
3
+ import { describe, expect, it } from "vitest";
4
+ import { render } from "@testing-library/svelte";
5
+ import <%= name %> from "./<%= name %>.svelte";
6
+
7
+ describe("<%= name %>", () => {
8
+ it("renders", () => {
9
+ render(<%= name %>);
10
+ // Add assertions based on your component
11
+ });
12
+
13
+ it("applies custom class", () => {
14
+ render(<%= name %>, { props: { class: "custom-class" } });
15
+ const element = document.querySelector(".<%= kebabName %>");
16
+ expect(element).toHaveClass("custom-class");
17
+ });
18
+ });
@@ -0,0 +1,9 @@
1
+ // Generated by <%= generatorName %> v<%= version %>
2
+
3
+ import type { Snippet } from "svelte";
4
+ import type { HTMLAttributes } from "svelte/elements";
5
+
6
+ export interface <%= name %>Props extends HTMLAttributes<HTMLDivElement> {
7
+ /** Content to render inside the component */
8
+ children?: Snippet;
9
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "@canonical/typescript-config-base",
3
+ "compilerOptions": {
4
+ "types": ["node", "bun-types"],
5
+ "jsx": "react-jsx",
6
+ "skipLibCheck": true
7
+ },
8
+ "include": ["src/**/*.ts"]
9
+ }