0
# Factory Functions
1
2
Factory functions provide convenient ways to create pre-configured Channel instances for common use cases, particularly browser-based Storybook setups with appropriate transport combinations.
3
4
## Capabilities
5
6
### Create Browser Channel
7
8
The primary factory function for creating browser-optimized channels with appropriate transports for Storybook Manager and Preview communication.
9
10
```typescript { .api }
11
/**
12
* Creates a new browser channel instance with appropriate transports
13
* Automatically configures PostMessage transport and optionally WebSocket transport
14
* @param options - Configuration options for the channel
15
* @returns Configured Channel instance ready for browser use
16
*/
17
function createBrowserChannel(options: Options): Channel;
18
19
interface Options {
20
/** Page identifier - determines transport configuration */
21
page: 'manager' | 'preview';
22
/** Optional additional transports to include */
23
extraTransports?: ChannelTransport[];
24
}
25
```
26
27
**Usage Examples:**
28
29
```typescript
30
import { createBrowserChannel } from "@storybook/channels";
31
32
// Create channel for Storybook Manager
33
const managerChannel = createBrowserChannel({ page: 'manager' });
34
35
// Create channel for Storybook Preview
36
const previewChannel = createBrowserChannel({ page: 'preview' });
37
38
// Create channel with extra transports
39
const enhancedChannel = createBrowserChannel({
40
page: 'manager',
41
extraTransports: [
42
new CustomTransport({ endpoint: '/api/events' })
43
]
44
});
45
46
// Use the channel
47
managerChannel.addListener('story-changed', (data) => {
48
console.log('Story changed in manager:', data);
49
});
50
51
managerChannel.emit('request-story-list');
52
```
53
54
### Transport Configuration
55
56
The factory function automatically configures appropriate transports based on the page type and environment.
57
58
**Default Transport Configuration:**
59
60
For `page: 'manager'`:
61
- PostMessageTransport configured for manager-side communication
62
- WebSocket transport (if available in development mode)
63
64
For `page: 'preview'`:
65
- PostMessageTransport configured for preview-side communication
66
- WebSocket transport (if available in development mode)
67
68
**Environment Detection:**
69
70
```typescript
71
// The factory function detects the environment and configures transports accordingly
72
// Development mode: PostMessage + WebSocket
73
// Production mode: PostMessage only
74
// Custom environments: PostMessage + extraTransports
75
```
76
77
### Advanced Factory Usage
78
79
Creating channels with custom transport combinations and configurations.
80
81
**Custom Transport Integration:**
82
83
```typescript
84
import { createBrowserChannel, WebsocketTransport } from "@storybook/channels";
85
86
// Create channel with custom WebSocket configuration
87
const customChannel = createBrowserChannel({
88
page: 'manager',
89
extraTransports: [
90
new WebsocketTransport({
91
url: 'wss://custom-storybook-server.com/ws',
92
onError: (error) => console.error('Custom WebSocket error:', error),
93
page: 'manager'
94
})
95
]
96
});
97
```
98
99
**Multiple Transport Scenarios:**
100
101
```typescript
102
// Channel with multiple custom transports
103
const multiTransportChannel = createBrowserChannel({
104
page: 'preview',
105
extraTransports: [
106
new WebsocketTransport({
107
url: 'ws://localhost:9001',
108
onError: (error) => console.error('WebSocket connection error:', error),
109
page: 'preview'
110
}),
111
new CustomHttpTransport({ endpoint: '/events' }),
112
new CustomServerSentEventsTransport({ url: '/sse' })
113
]
114
});
115
```
116
117
## Utility Functions
118
119
### Event Source URL Detection
120
121
Utility function for determining the source URL of postMessage events, used internally by the PostMessage transport.
122
123
```typescript { .api }
124
/**
125
* Determines the source URL of a postMessage event
126
* Used internally for validating and routing postMessage communications
127
* @param event - MessageEvent from postMessage listener
128
* @returns Source URL string or null if unable to determine
129
*/
130
function getEventSourceUrl(event: MessageEvent): string | null;
131
```
132
133
**Usage Examples:**
134
135
```typescript
136
import { getEventSourceUrl } from "@storybook/channels";
137
138
// Used internally by PostMessage transport
139
window.addEventListener('message', (event) => {
140
const sourceUrl = getEventSourceUrl(event);
141
142
if (sourceUrl && isAllowedOrigin(sourceUrl)) {
143
// Process the message
144
handleChannelMessage(event.data);
145
}
146
});
147
148
// Custom implementation example
149
function isAllowedOrigin(url: string): boolean {
150
const allowedOrigins = [
151
'http://localhost:6006',
152
'https://your-storybook.netlify.app'
153
];
154
155
return allowedOrigins.some(origin => url.startsWith(origin));
156
}
157
```
158
159
## Factory Function Benefits
160
161
**Simplified Setup:**
162
- Eliminates boilerplate transport configuration
163
- Provides sensible defaults for browser environments
164
- Handles environment detection automatically
165
166
**Consistency:**
167
- Ensures consistent transport configuration across different parts of Storybook
168
- Reduces configuration errors and inconsistencies
169
- Maintains compatibility with Storybook's internal expectations
170
171
**Extensibility:**
172
- Supports additional transports through `extraTransports` option
173
- Allows customization while maintaining core functionality
174
- Facilitates testing and development workflows
175
176
**Environment Adaptation:**
177
- Automatically adapts to development vs production environments
178
- Handles transport availability gracefully
179
- Provides fallback mechanisms for constrained environments