blob: 76b7085f6b1febaf4ee908365053310ad775027a [file] [log] [blame]
Sean McCullough618bfb22025-06-25 20:52:30 +00001/**
2 * Demo runner that dynamically loads and executes demo modules
3 */
4
5import {
6 DemoModule,
7 DemoRegistry,
8 DemoRunnerOptions,
9 DemoNavigationEvent,
10} from "./types";
11
12export class DemoRunner {
13 private container: HTMLElement;
14 private basePath: string;
15 private currentDemo: DemoModule | null = null;
16 private currentComponentName: string | null = null;
17 private onDemoChange?: (componentName: string, demo: DemoModule) => void;
18
19 constructor(options: DemoRunnerOptions) {
20 this.container = options.container;
21 this.basePath = options.basePath || "../";
22 this.onDemoChange = options.onDemoChange;
23 }
24
25 /**
26 * Load and display a demo for the specified component
27 */
28 async loadDemo(componentName: string): Promise<void> {
29 try {
30 // Cleanup current demo if any
31 await this.cleanup();
32
33 // Dynamically import the demo module
34 const demoModule = await import(
35 /* @vite-ignore */ `../${componentName}.demo.ts`
36 );
37 const demo: DemoModule = demoModule.default;
38
39 if (!demo) {
40 throw new Error(
41 `Demo module for ${componentName} does not export a default DemoModule`,
42 );
43 }
44
45 // Clear container
46 this.container.innerHTML = "";
47
48 // Load additional styles if specified
49 if (demo.styles) {
50 for (const styleUrl of demo.styles) {
51 await this.loadStylesheet(styleUrl);
52 }
53 }
54
55 // Add custom styles if specified
56 if (demo.customStyles) {
57 this.addCustomStyles(demo.customStyles, componentName);
58 }
59
60 // Import required component modules
61 if (demo.imports) {
62 for (const importPath of demo.imports) {
63 await import(/* @vite-ignore */ this.basePath + importPath);
64 }
65 }
66
67 // Set up the demo
68 await demo.setup(this.container);
69
70 // Update current state
71 this.currentDemo = demo;
72 this.currentComponentName = componentName;
73
74 // Notify listeners
75 if (this.onDemoChange) {
76 this.onDemoChange(componentName, demo);
77 }
78
79 // Dispatch navigation event
80 const event: DemoNavigationEvent = new CustomEvent("demo-navigation", {
81 detail: { componentName, demo },
82 });
83 document.dispatchEvent(event);
84 } catch (error) {
85 console.error(`Failed to load demo for ${componentName}:`, error);
86 this.showError(`Failed to load demo for ${componentName}`, error);
87 }
88 }
89
90 /**
91 * Get list of available demo components by scanning for .demo.ts files
92 */
93 async getAvailableComponents(): Promise<string[]> {
94 // For now, we'll maintain a registry of known demo components
95 // This could be improved with build-time generation
96 const knownComponents = [
97 "sketch-chat-input",
98 "sketch-container-status",
99 "sketch-tool-calls",
bankseand5c849d2025-06-26 15:48:31 +0000100 "sketch-view-mode-select",
Sean McCullough618bfb22025-06-25 20:52:30 +0000101 ];
102
103 // Filter to only components that actually have demo files
104 const availableComponents: string[] = [];
105 for (const component of knownComponents) {
106 try {
107 // Test if the demo module exists by attempting to import it
108 const demoModule = await import(
109 /* @vite-ignore */ `../${component}.demo.ts`
110 );
111 if (demoModule.default) {
112 availableComponents.push(component);
113 }
114 } catch (error) {
115 console.warn(`Demo not available for ${component}:`, error);
116 // Component demo doesn't exist, skip it
117 }
118 }
119
120 return availableComponents;
121 }
122
123 /**
124 * Cleanup current demo
125 */
126 private async cleanup(): Promise<void> {
127 if (this.currentDemo?.cleanup) {
128 await this.currentDemo.cleanup();
129 }
130
131 // Remove custom styles
132 if (this.currentComponentName) {
133 this.removeCustomStyles(this.currentComponentName);
134 }
135
136 this.currentDemo = null;
137 this.currentComponentName = null;
138 }
139
140 /**
141 * Load a CSS stylesheet dynamically
142 */
143 private async loadStylesheet(url: string): Promise<void> {
144 return new Promise((resolve, reject) => {
145 const link = document.createElement("link");
146 link.rel = "stylesheet";
147 link.href = url;
148 link.onload = () => resolve();
149 link.onerror = () =>
150 reject(new Error(`Failed to load stylesheet: ${url}`));
151 document.head.appendChild(link);
152 });
153 }
154
155 /**
156 * Add custom CSS styles for a demo
157 */
158 private addCustomStyles(css: string, componentName: string): void {
159 const styleId = `demo-custom-styles-${componentName}`;
160
161 // Remove existing styles for this component
162 const existing = document.getElementById(styleId);
163 if (existing) {
164 existing.remove();
165 }
166
167 // Add new styles
168 const style = document.createElement("style");
169 style.id = styleId;
170 style.textContent = css;
171 document.head.appendChild(style);
172 }
173
174 /**
175 * Remove custom styles for a component
176 */
177 private removeCustomStyles(componentName: string): void {
178 const styleId = `demo-custom-styles-${componentName}`;
179 const existing = document.getElementById(styleId);
180 if (existing) {
181 existing.remove();
182 }
183 }
184
185 /**
186 * Show error message in the demo container
187 */
188 private showError(message: string, error: any): void {
189 this.container.innerHTML = `
190 <div style="
191 padding: 20px;
192 background: #fee;
193 border: 1px solid #fcc;
194 border-radius: 4px;
195 color: #800;
196 font-family: monospace;
197 ">
198 <h3>Demo Error</h3>
199 <p><strong>${message}</strong></p>
200 <details>
201 <summary>Error Details</summary>
202 <pre>${error.stack || error.message || error}</pre>
203 </details>
204 </div>
205 `;
206 }
207
208 /**
209 * Get current demo info
210 */
211 getCurrentDemo(): { componentName: string; demo: DemoModule } | null {
212 if (this.currentComponentName && this.currentDemo) {
213 return {
214 componentName: this.currentComponentName,
215 demo: this.currentDemo,
216 };
217 }
218 return null;
219 }
220}